The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Internet Domains 1213

The protocol is typically either tcp or udp. The optional (space-delimited) aliases specify
alternative names for the service. In addition to the above, lines may include com-
ments starting with the # character.
As noted previously, a given port number refers to distinct entities for UDP
and TCP, but IANA policy assigns both port numbers to a service, even if that service
uses only one protocol. For example, telnet, ssh, HTTP, and SMTP all use TCP, but
the corresponding UDP port is also assigned to these services. Conversely, NTP
uses only UDP, but the TCP port 123 is also assigned to this service. In some cases,
a service uses both UDP and TCP; DNS and echo are examples of such services.
Finally, there are a very few cases where the UDP and TCP ports with the same
number are assigned to different services; for example, rsh uses TCP port 514,
while the syslog daemon (Section 37.5) uses UDP port 514. This is because these
port numbers were assigned before the adoption of the present IANA policy.

The /etc/services file is merely a record of name-to-number mappings. It is not
a reservation mechanism: the appearance of a port number in /etc/services
doesn’t guarantee that it will actually be available for binding by a particular
service.

59.10 Protocol-Independent Host and Service Conversion


The getaddrinfo() function converts host and service names to IP addresses and port
numbers. It was defined in POSIX.1g as the (reentrant) successor to the obsolete
gethostbyname() and getservbyname() functions. (Replacing the use of gethostbyname()
with getaddrinfo() allows us to eliminate IPv4-versus-IPv6 dependencies from our
programs.)
The getnameinfo() function is the converse of getaddrinfo(). It translates a socket
address structure (either IPv4 or IPv6) to strings containing the corresponding host
and service name. This function is the (reentrant) equivalent of the obsolete
gethostbyaddr() and getservbyport() functions.

Chapter 11 of [Stevens et al., 2004] describes getaddrinfo() and getnameinfo() in
detail, and provides implementations of these functions. These functions are
also described in RFC 3493.

59.10.1 The getaddrinfo() Function


Given a host name and a service name, getaddrinfo() returns a list of socket address
structures, each of which contains an IP address and port number.

#include <sys/socket.h>
#include <netdb.h>

int getaddrinfo(const char *host, const char *service,
const struct addrinfo *hints, struct addrinfo **result);
Returns 0 on success, or nonzero on error
Free download pdf