1234 Chapter 59
printf(" address type: %s\n",
(h->h_addrtype == AF_INET)? "AF_INET" :
(h->h_addrtype == AF_INET6)? "AF_INET6" : "???");
if (h->h_addrtype == AF_INET || h->h_addrtype == AF_INET6) {
printf(" address(es): ");
for (pp = h->h_addr_list; *pp != NULL; pp++)
printf(" %s", inet_ntop(h->h_addrtype, *pp,
str, INET6_ADDRSTRLEN));
printf("\n");
}
}
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––– sockets/t_gethostbyname.c
59.13.3 The getservbyname() and getservbyport() Functions
The getservbyname() and getservbyport() functions retrieve records from the /etc/services
file (Section 59.9). These functions are nowadays made obsolete by getaddrinfo() and
getnameinfo().
The getservbyname() function looks up the record whose service name (or one of its
aliases) matches name and whose protocol matches proto. The proto argument is a
string such as tcp or udp, or it can be NULL. If proto is specified as NULL, any record
whose service name matches name is returned. (This is usually sufficient since,
where both UDP and TCP records with the same name exist in the /etc/services
file, they normally have the same port number.) If a matching record is found, then
getservbyname() returns a pointer to a statically allocated structure of the following type:
struct servent {
char *s_name; /* Official service name */
char **s_aliases; /* Pointers to aliases (NULL-terminated) */
int s_port; /* Port number (in network byte order) */
char *s_proto; /* Protocol */
};
Typically, we call getservbyname() only in order to obtain the port number, which is
returned in the s_port field.
The getservbyport() function performs the converse of getservbyname(). It returns
a servent record containing information from the /etc/services record whose port
number matches port and whose protocol matches proto. Again, we can specify proto
as NULL, in which case the call will return any record whose port number matches
#include <netdb.h>
struct servent *getservbyname(const char *name, const char *proto);
struct servent *getservbyport(int port, const char *proto);
Both return pointer to a (statically allocated) servent structure
on success, or NULL on not found or error