Determining the Protocol Argument for Socket

 < Day Day Up > 



Recall that when we created a simple stream socket, the third argument was defined as zero. This meant that the socket function would pick the default protocol for the given type (such as SOCK_STREAM). In this case, the default protocol is TCP, but what is the actual protocol number for TCP?

This question can be answered using the getprotobyname function. Function getprotobyname can be used to return the actual protocol number associated with the given protocol string (such as “tcp”). Let’s look at a simple example that enumerates some of the standard protocols found in the IP suite (see Listing 6.16).

Listing 6.16 Finding the unique protocol number (proto.c).

start example
#include <netdb.h> main() {   struct protoent *pp;   pp = getprotobyname( "ip" );   if (pp) printf(" ip = %d\n", pp->p_proto );   pp = getprotobyname( "icmp" );   if (pp) printf(" icmp = %d\n", pp->p_proto );   pp = getprotobyname( "igmp" );   if (pp) printf(" igmp = %d\n", pp->p_proto );   pp = getprotobyname( "tcp" );   if (pp) printf(" tcp = %d\n", pp->p_proto );   pp = getprotobyname( "udp" );   if (pp) printf(" udp = %d\n", pp->p_proto );   pp = getprotobyname( "rdp" );   if (pp) printf(" rdp = %d\n", pp->p_proto ); }
end example

The function getprotobyname returns a protocol entry, of which the p_proto field is the protocol number (which can be used as the protocol argument of the socket function). The protocol numbers for the protocols shown in Listing 6.16 are shown in Table 6.1.

Table 6.1: PROTOCOL NUMBERS FOR TYPICAL IP PROTOCOLS

Protocol

Protocol Number

IP

0

ICMP

1

IGMP

2

TCP

6

UDP

17

RDP

27

Use of the getprotobyname function is shown in Listing 6.17. This illustrates formal use of the getprotobyname function to return the protocol number for use by socket.

Listing 6.17 Using getprotobyname for the socket function.

start example
#include <netdb.h> ... int sock; struct protoent *pp; /* Get the TCP protocol entry */ pp = getprotobyname( "tcp" ); /* Create a TCP socket */ if (pp) {   sock = socket( AF_INET, SOCK_STREAM, pp->p_proto ); }
end example

The code in Listing 6.17 has the same effect as creating a socket using the default protocol, such as:

    sock = socket( AF_INET, SOCK_STREAM, 0 );

The location of the protocol numbers differs based upon the target system, but on Linux systems, this file can be found at /etc/protocols.



 < 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