| < Day Day Up > |
|
The getservbyport function can be used to identify the service and its characteristics given a port number. The result of the getservbyport function is identical to that of getservbyname, but how these results are achieved differs. The prototype for the getservbyport function is defined as:
#include <netdb.h> struct servent *getservbyport( int port, const char *proto );
The port argument is the port number for the desired service in network byte order. The proto argument (protocol) specifies the particular Transport layer protocol used by the service. As with getservbyname, this field is optional. An example of the getservbyport function is shown in Listing 4.14.
Listing 4.14 Example of the getservbyport function.
#include <netdb.h> struct servent *sp; ... sp = getservbyport( htons(80), NULL ); if (sp) { printf( "Service %s is at port %d\n", sp->s_name, ntohs( sp->s_port ) ); }
The database that’s used by the getservbyname and getservbyport functions is commonly found in Unix systems in the /etc/services file. This file (a sample of which is shown in Listing 4.15) provides a line per service and includes the official service name, the port number, the transport protocol, and a set of aliases (note the mapping back to the servent structure). The location of this file may differ depending upon the operating system, and may be hard coded into the source of an embedded systems stack.
Listing 4.15 Sample of a Unix /etc/services file.
#Service Port/Proto Aliases discard 9/tcp sink null discard 9/udp sink null daytime 13/tcp daytime 13/udp ftp 21/tcp smtp 25/tcp mail www 80/tcp http www 80/udp
The value of the service functions is that they allow applications to be built without having to hard code the service port numbers (and protocols) directly into the source. This permits more flexible applications and simpler maintenance.
| < Day Day Up > |
|