In the network transmission layer, apart from common TCP transmission, UDP is also used for transmission. In this case, we seldom use the socket program to send UDP protocol data. First, we should understand the following concepts: UDP is a simple datagram-oriented transport layer protocol. Let's first look at how to send a UDP datagram from the perspective of the UDP client, and what the protocol stack does to send a UDP datagram. UDP datagram can be sent using sendto system call on an unconnected socket to specify the destination address), or sent using the send system call on a connected socket without specifying the destination address ), we will discuss it in two cases.
The following is an example of a user-State program that sends UDP data on an unconnected socket. Note: The format and style of the program are rather bad, but they are used for temporary testing .), This program only sends messages and does not process the messages. We will analyze the messages later:
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <sys/ioctl. h>
# Include "my_inet.h"
# Include <stdio. h>
# Include <errno. h>
# Include <arpa/inet. h>
# Include <unistd. h>
Intmain ()
{
Inti;
Structsockaddr_indest;
Dest. sin_family = MY_PF_INET;
Dest. sin_port = htons (16000 );
Dest. sin_addr.s_addr = 0x013010AC; // the destination address is 172.16.48.1 (Network byte order)
// Create the socket of the UDP datagram service.
Intfd = socket (MY_PF_INET, SOCK_DGRAM, MY_IPPROTO_UDP );
If (fd <0 ){
Perror ("socket :");
Return-1;
}
Intbwrite = sendto (fd, "abcdefg", 7,0, (structsockaddr *) & dest, sizeof (dest ));
If (bwrite =-1 ){
Perror ("send :");
Close (fd );
Return-1;
}
Printf ("sendto: % d \ n", bwrite );
Close (fd );
Return0;
}
The operation of creating a socket is similar to that of the RAW protocol. The operation set in the structure of the socket is represented in the kernel, and the protocol name is slightly different. We focus on the kernel code execution caused by the sendto operation. The first stop of the my_inet module reached by sendto is myinet_sendmsg. Generally, this function only needs to call the udp_sendmsg Of The UDP protocol, but before that, it has to do the same thing, this is to bind the socket, which may be different from the bind System Call on the server. Imagine if we use this UDPsocket to send a datagram but do not record this UDPsocket, when the peer responds to the datagram, we do not know which socket will receive this datagram. Binding is to record this UDPsocket.