ptg10805159
600 Network IPC: Sockets Chapter 16
Theaddrinfostructure is defined to include at least the following members:
struct addrinfo {
int ai_flags; /* customize behavior */
int ai_family; /* address family */
int ai_socktype; /* socket type */
int ai_protocol; /* protocol */
socklen_t ai_addrlen; /* length in bytes of address */
struct sockaddr *ai_addr; /* address */
char *ai_canonname; /* canonical name of host */
struct addrinfo *ai_next; /* next in list */
..
.
};
We can supply an optionalhintto select addresses that meet certain criteria. The
hint is a template used for filtering addresses and uses only the ai_family,
ai_flags,ai_protocol,andai_socktypefields. The remaining integer fields
must be set to 0, and the pointer fields must be null. Figure16.7 summarizes the flags
we can use in theai_flagsfield to customize how addresses and names aretreated.
Flag Description
AI_ADDRCONFIG Query for whichever address type(IPv4 or IPv6)is configured.
AI_ALL Look for both IPv4 and IPv6 addresses (used only withAI_V4MAPPED).
AI_CANONNAME Request a canonical name (as opposed to an alias).
AI_NUMERICHOST The host address is specified in numeric format; don’t try to translate it.
AI_NUMERICSERV The service is specified as a numeric port number; don’t try to translate it.
AI_PASSIVE Socket address is intended to be bound for listening.
AI_V4MAPPED If no IPv6 addresses arefound, return IPv4 addresses mapped in IPv6 format.
Figure 16.7 Flags foraddrinfostructure
Ifgetaddrinfofails, we can’t useperrororstrerrorto generate an error
message. Instead, we need to callgai_strerrorto convert the error code returned
into an error message.
#include <netdb.h>
const char *gai_strerror(interror);
Returns: a pointer to a string describing the error
Thegetnameinfofunction converts an address into host and service names.
#include <sys/socket.h>
#include <netdb.h>
int getnameinfo(const struct sockaddr *restrictaddr,socklen_t alen,
char *restricthost,socklen_t hostlen,
char *restrictservice,socklen_tservlen,intflags);
Returns: 0 if OK, nonzero on error