TCP/IP Programming Manual
service
input value; specifies a pointer to a character representing one of the following:
• A network service name.
• A decimal port number.
• NULL if no service name requires converting; when NULL is used, either hostname or hints
must be non-NULL.
hints
input value; specifies one of the following:
• A pointer to an addrinfo struct for a socket; the format of the addrinfo structure is
defined in the header file netdb.h.
• NULL if no struct is available; when NULL is used, either hostname or service must
be non-NULL.
result
return value; points to a list of addrinfo structs upon successful completion. (See Usage
Guidelines (page 108).)
Example
This fragment of an IPv6 TCP Client shows a client that requests a service called example.
struct addrinfo *res, *ainfo;
struct addrinfo hints;
/* clear out hints */
memset ((char *)&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
error = getaddrinfo(argv[1], "example", &hints, &res);
if (error != 0) {
fprintf(stderr, "%s: %s not found in name service database\n",
argv[0], argv[1]);
exit(1);
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
/* Create the socket. */
s = socket (ainfo->ai_family,ainfo->ai_socktype,
ainfo->ai_protocol);
if (s == -1) {
perror(argv[0]);
fprintf(stderr, "%s: unable to create socket\n", argv[0]);
freeaddrinfo(res);
exit(1);
}
if (connect(s, ainfo->ai_addr, ainfo->ai_addrlen) == -1){
perror(argv[0]);
fprintf(stderr, "%s: unable to connect to remote\n", argv[0]);
FILE_CLOSE(S);
continue;
}
else
break;
}
Usage Guidelines
• This function, along with getipnodebyname (page 116), are protocol-independent replacements
for gethostbyname, host_file_gethostbyname (page 110). getaddrinfo provides extra
108 Library Routines