Here we will describe the last socket combination that you will use in the applications within this book. The combination of PF_INET and SOCK_DGRAM causes the kernel to choose the UDP protocol. UDP is short for User Datagram Protocol. A datagram is a standalone packet of information.
This protocol allows the application to send datagrams from your socket to the remote socket, to which you have addressed it. Note again that this service is not reliable, but it is suitable for many types of services in which efficiency is highly desirable. For example, the Network Time Protocol (NTP) uses UDP because it is efficient and message-oriented, and lost messages can be tolerated.
The impact of a lost message is that the time synchronization might take longer to achieve or that some accuracy is lost when expecting replies from multiple NTP servers. To create a UDP socket, you can use zero for the protocol argument. The following shows an example:
Example
int s;
s = socket(PF_INET,SOCK_DGRAM,0);
if ( s == -1 )
{
perror("socket()");
}
The procedure used is the same general procedure that has been used in the preceding sections. However, the arguments used in the socket(2) function require explanation:
- 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_DGRAM to request a datagram socket.
- The protocol argument is specified as zero to allow the kernel to choose the correct protocol for the PF_INET and SOCK_DGRAM combination.
Example
However, if you prefer to specify UDP explicitly, you might do it like this instead:
int s;
s = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
if ( s == -1 )
{
perror("socket()");
}
The arguments for this socket(2) call are described 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_DGRAM to request a datagram socket.
- The protocol argument is specified as IPPROTO_UDP to explicitly indicate that only the UDP protocol is permitted for this socket.
There is a number of other socket combinations that can be created, but these are too advanced to be considered here. You will be happy to know that most of the time you will use only the four socket(2) parameter combinations that have just been described and are summarized in table below.
Domain | Socket Type | Protocol | Description |
PF_LOCAL | SOCK_STREAM | 0 | stream socket |
PF_LOCAL | SOCK_DGRAM | 0 | datagram socket |
PF_INET | SOCK_STREAM | IPPROTO_TCP | TCP/IP stream socket |
PF_INET | SOCK_DGRAM | IPPROTO_UDP | datagram socket |
Note that the last two entries (domain PF_INET) shown in Table above may have zero specified instead for the protocol argument. This decision is left to the discretion of the programmer.
No comments:
Post a Comment