Unix Network Programming Manual
Getting Services Data
Another category of information that you need to manipulate is that for
services. Again, it is inconvenient to always know what port number to
use and to hard code it into a program. Services have names, ports and
protocols, as defined by the structure:
struct servent
{
char *s_name; /* official name of service */
char **s_aliases; /* alias list */
long s_port; /* port service resides at */
char *s_proto; /* protocol to use */
};
You can specify either a name or a port and obtain this service
structure for a particular service using getservbyname or
getservbyport.
struct servent *getservbyname (name, proto)
char *name
char *proto
struct servent *getservbyport (port, proto)
int port
char *proto
For example, if you had a stream server that could by known by several
different service names (ports-protocol pairs), you might pass in the
service name that you want it to use. The server could find the appropriate
port number for the bind as follows:
struct servent *serv;
struct sockaddr_in addr;
unsigned short port;
serv = getservbyname (args[1], "tcp");
port = serv -> s_port;
.
.
addr.sin_family = AF_INET;
addr.sin_port = port;
addr.sin_addr.s_addr = htonl (INADDR_ANY);
if (bind(sock, &addr, sizeof (struct sockaddr_in)) == -1)
.
.
In this case, you have to know that the server is written for streams
and that the protocol for Internet streams is tcp.
getservbyport is used less frequently but might be used to determine
the service name being used from the port number, since the service name
will probably have more meaning to the humans than a port number.