At the present time, a zero in the protocol argument of the socket(2) function for the domain PF_INET will cause the kernel to choose IPPROTO_TCP. This causes the socket to use the TCP/IP protocol. The TCP part of the TCP/IP designation is the transport level protocol that is built on top of the IP layer. This provides the data packet sequencing, error control, and recovery.
In short, TCP makes it possible to provide a stream socket using the Internet protocol. As you see in the following example, most application programmers will choose to simply specify the protocol argument as zero, allowing the kernel to correctly choose the protocol:
s = socket(PF_INET,SOCK_STREAM,0);
if ( s == -1 )
The steps used to create Internet stream sockets are
- Integer s is declared to receive the socket number.
- The socket(2) function is called. The domain argument is set to PF_INET to choose the Internet family of protocols. The socket type argument is set to SOCK_STREAM to request a stream socket. The protocol argument is set to zero, which allows the kernel to choose the correct protocol for the combination of PF_INET and SOCK_STREAM.
- The value s is tested to see whether it is the value -1. If it is, then an error has occurred, and errno has the reason for it. Function perror(3) is used in this example to report what the errno code indicates.
- If s is not -1, then it represents a valid socket. It can be used in most places where a file descriptor is valid (in read(2) and write(2) function calls, for example).
Specifying zero for the protocol argument of socket(2) will imply the use of TCP/IP. However, if you like having full control, or worry that future kernel defaults might be unsuitable, you can
explicitly choose the protocol as follows:
s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if ( s == -1 )
Looking only at the socket(2) function call, the arguments can be explained as follows:
- The domain argument is specified as PF_INET as before, to indicate that the Internet family of protocols is required.
- The socket type argument is specified as SOCK_STREAM to request a stream I/O socket, as before.
- The protocol argument, however, has been explicitly specified as IPPROTO_TCP in this case.
This chooses the use of the TCP/IP protocol for this socket.
The IPPROTO_TCP macro is defined by the include file: