| < Day Day Up > |
|
A number of interesting functions exist to retrieve information about known services in a Unix-based system. Each of the functions returns a servent structure that defines not only the service name and port, but also the protocol by which it should be accessed and any aliases that exist for it. Some of the more common service functions are:
struct servent *getservbyname( const char *name, const char *proto );
which is used to retrieve service information for a service given its name and protocol (such as “tcp”). Services can also be retrieved by port number using the following function prototype:
struct servent *getservbyport( int port, const char *proto );
We can also simply enumerate the known services of a system using the getservent function. This function requires the initialization function startservent and the completion function endservent, which all have the following prototypes:
void startservent( int stayopen ); void endservent( void ); struct servent *getservent( void );
We first call startservent to begin our enumeration, specifying by default an argument of zero to allow the services file to be closed. This starts us off at the beginning of the services table. Subsequent calls to getservent return the next services entry in the table. After we’ve enumerated all of the services, a call to endservent halts the enumeration (and closes the services file if we’ve requested that it stay open with startservent).
The example shown in Listing 6.18 illustrates enumerating the service entries of the services table. After starting our enumeration with startservent, we simply walk through the table using getservent, emitting some information about the service for each one found. When completed, we call endservent.
The information we emit is the service name (official name), port number used by the service (for the given protocol), and finally the protocol that should be used to access the service (such as “tcp” or “udp”).
Listing 6.18 Enumerating the services table (servenum.c).
#include <netdb.h> main() { struct servent *sp; /* Start the service enumeration */ setservent( 0 ); while (1) { /* Get the next service row */ sp = getservent(); if (sp != NULL) { printf("Service %s is at port %d for %s\n", sp->s_name, ntohs(sp->s_port), sp->s_proto); } else break; } /* End the service enumeration */ endservent(); }
It’s important to note that this function simply enumerates the services table and does not necessarily mean that these services are available on the given node (or any other node for that matter). What these functions provide is the ability to specify a service name and then identify the port number and protocol that may be used to access the service.
| < Day Day Up > |
|