getservbyport Function

 < Day Day Up > 



getservbyport Function

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.

start example
#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 ) ); }
end example

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.

start example
#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
end example

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 > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net