Monday, August 15, 2011

Using the endservent(3) Function


The function getservent(3) opens the /etc/services file behind the scenes, before returning a pointer to an entry. If your application has determined that it no longer needs to read more entries, then the endservent(3) function can be used to cause the file to be closed. This is especially important in server programs where the number of open file descriptors may be at a premium. The function synopsis is as follows:

#include <netdb.h>
void endservent(void);

There is no argument, no return value, and no errors to test.
Looking up a Service by Name and Protocol The previously introduced functions enable you to scan the /etc/services file one entry at a time. Often, however, this still proves to be inconvenient because of the amount of code involved. Instead, it would be more convenient to supply the service name and protocol, and have a function return the required entry. The getservbyname(3) function does just that. The function synopsis is as follows:

#include <netdb.h>
struct servent *getservbyname(const char *name, const char *proto);

The arguments to the function are as follows:
  1. The service name to look up. For example, "telnet" could be used.
  2. The protocol to be used (proto). Often a service will be available using UDP or TCP/IP.

Consequently, you must specify the protocol that you are willing to use in order to contact that service. An example would be "tcp." The value returned is NULL if the service cannot be found. Otherwise, a pointer to a structure servent is returned. An example of its use is shown as follows:

Example

struct servent *sp;
sp = getservbyname ("telnet","tcp");
if ( !sp ) {
   abort(); /* No such service! */
}

If the function call is successful, the structure pointer sp will point to all of the pertinent details, including the port number.

CAUTION
The pointer returned by getservbyname(3) is only valid until the next call to the same function. Looking up a Service by Port and Protocol You saw in the last section that it was possible to look up a service by name and protocol. The function getservbyport(3) allows you to also perform a lookup by port and protocol. The function synopsis is as follows:

#include <netdb.h>
struct servent *getservbyport(int port, const char *proto);

The function arguments are as follows:
  1. The port number for this Internet protocol.
  2. The protocol proto to be looked up for port.

The function returns a NULL pointer if no service entry can be found to match your input parameters. Otherwise, a pointer is returned to the structure containing information, such as the service name, for example.

CAUTION
The pointer returned by getservbyport(3) is only valid until the next call to the same function.

No comments:

Post a Comment