Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

604 Network IPC: Sockets Chapter 16


sinp = (struct sockaddr_in *)aip->ai_addr;
addr = inet_ntop(AF_INET, &sinp->sin_addr, abuf,
INET_ADDRSTRLEN);
printf(" address %s", addr?addr:"unknown");
printf(" port %d", ntohs(sinp->sin_port));
}
printf("\n");
}
exit(0);
}

Figure 16.9 Print host and service information

This program illustrates the use of thegetaddrinfofunction. If multiple protocols
provide the given service for the given host, the program will print morethan one entry.
In this example, we print out the address information only for the protocols that work
with IPv4 (ai_familyequalsAF_INET). If we wanted to restrict the output to the
AF_INETprotocol family, we could set theai_familyfield in the hint.
When we run the program on one of the test systems, we get
$./a.out harry nfs
flags canon family inet type stream protocol TCP
host harry address 192.168.1.99 port 2049
flags canon family inet type datagram protocol UDP
host harry address 192.168.1.99 port 2049

16.3.4 Associating Addresses with Sockets


The address associated with a client’s socket is of little interest, and we can let the
system choose a default address for us. For a server,however, we need to associate a
well-known address with the server ’s socket on which client requests will arrive.
Clients need a way to discover the address to use to contact a server,and the simplest
scheme is for a server to reserve an address and register it in/etc/servicesor with a
name service.
We use thebindfunction to associate an address with a socket.

#include <sys/socket.h>
int bind(intsockfd,const struct sockaddr *addr,socklen_tlen);
Returns: 0 if OK,−1 on error

Thereare several restrictions on the address we can use:

•The address we specify must be valid for the machine on which the process is
running; we can’t specify an address belonging to some other machine.
•The address must match the format supported by the address family we used to
create the socket.
Free download pdf