Linux interprocess communication-datagram socket sockets (), bind (), sendto (), Recvfrom (), Close ()

Source: Internet
Author: User
Tags htons

Previous article, Linux interprocess communication--using flow sockets to introduce some basic content about sockets (sockets), and to explain the use of the flow sockets, this article will tell you, the use of datagram sockets.

a simple review-what is a datagram socket

A socket, or socket, is a communication mechanism whereby the development of a client/server (that is, the process of communicating) can be done on a local machine or across a network. This means that it can communicate with processes that are not on the same computer but are connected over the network to the computer. Because of this, the socket explicitly distinguishes the client from the server.

The use of a datagram socket is simpler than a stream socket, which is specified by type SOCK_DGRAM, which does not need to establish a connection and maintain a connection, which is usually implemented through the UDP/IP protocol in Af_inet. It has a limit on the length of data that can be sent, the datagram is transmitted as a separate network message, it may be lost, copied, or garbled, and UDP is not a reliable protocol, but it is relatively fast because it needs to always establish and maintain a connection.

second, flow socket-based client/server workflow

How does the client/server system that uses the datagram socket for process communication work?

1. Server-side

Like using a flow socket, the server application first uses the system call socket () to create a socket, which is a resource that the system allocates to a similar file descriptor for the server process, and it cannot be shared with other processes.

Next, the server process gives the socket a name (listen), and we use the system call bind () to name the socket. The server process then begins to wait for the client to connect to the socket.

The difference is that the system then calls Recvfrom () to receive the data sent from the client program. The server program handles the data accordingly and sends the processed data back to the client through the system call SendTo ().

Compared to a streaming socket program:

    • In a program in a stream socket, the received data is called by the system to read, and the sending data is implemented through the system call to write (), which is implemented through Recvfrom () and sendto () calls in the datagram socket program.
    • A server program that uses a datagram socket does not require the listen () call to create a queue to store the connection, nor does it require the accept () invocation to receive the connection and create a new socket descriptor

2, the Client

Clients based on the datagram socket are simpler than the server side, and the client application first calls the socket to create an unnamed socket, and as with the server, the customer sends the data to the server and receives the data from the server program by SendTo () and Recvfrom ().

Compared to a streaming socket program:

A client program that uses a datagram socket does not need to use the Connect () system calls to connect to a server program, as long as it sends information to the IP port that the server listens to and receives data sent back from the server when it is needed.

third, the interface and function of the data report socket

The socket's interface functions are declared in the header files sys/types.h and sys/socket.h .

1. Create socket--socket () system call

The function is used to create a socket and return a descriptor that can be used to access the socket, which is prototyped as follows:

int socket(int domain, int type, int protocol);

The three parameters in the function correspond to the three socket properties mentioned earlier. The protocol parameter is set to 0 to indicate that the default protocol is used.

2. Named (bound) socket--bind () system call

This function names the socket created through the socket () call, allowing it to be used by other processes. For Af_unix, when the function is called, the socket is associated to a file system pathname, and for af_inet, it is associated to an IP port number. The function prototypes are as follows:

int bind(int socket, const struct SOCKADDR *address, size_t Address_len);

Returns 0 on success, 1 when failed;

3. Send data--sendto () system call

The function sends the information in buffer buffers to the specified IP port program, with the following prototype:

int sendto(int sockfd, void *buffer, size_t len, int flags, struct sockaddr *to, socklen_t Tolen);

The data to be sent is stored in buffer, Len is the length of buffer, and flags is usually set in the application to 0,to is the IP port of the program to send the data to, and Tolen is the length of the to parameter.

Returns the number of bytes of data sent when successful, and 1 on failure.

4. Receiving data--recvfrom () system call

The function stores the information sent to the program in buffer buffers and logs the program IP port of the data source, which is prototyped as follows:

int recvfrom(int sockfd, void *buffer, size_t len,int flags, struct sockaddr *src_from, socklen_t *src_len);

Buffer is used to store the received data, Len specifies the length of buffer, and flags is usually set in the application 0,src_from if not empty, the IP port of the data source program is logged, and if Src_len is not empty, its length information is recorded in SRC_ The variable that Len points to.

Note: By default, Recvfrom () is a blocking call that is not returned until it receives the data.

5. Close Socket--close () system call

This system call is used to terminate the socket connection on the server and the client, and we should always close the socket at both ends of the connection (server and client).

Iv. process uses datagram sockets for communication

The following uses multiple client program instances and a server program to demonstrate how multiple processes communicate by using a datagram socket.

SOCKSERVER2.C is a server program that receives data from the client program and creates a subprocess to process the data sent by the customer, and the process is very simple, which is to change the uppercase letters to lowercase. The processed data is then sent back to the client with the lowercase letter corresponding to the uppercase letters.

SOCKCLIENT2.C is a client program that sends data to the server program and receives the processed data sent by the server (that is, lowercase letters), and then outputs the received data to the screen. When you run the client, you can give it a character as a parameter, at which point the client sends some characters as the data to be processed to the server, and if you do not provide a parameter, the character a is sent by default.

The source code for SOCKSERVER2.C is as follows:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <signal.h>int main (int arc, char **argv) {int server_sockfd = -1;socklen_t Server_len = 0;socklen_t Client_len = 0;char buffer[512];ssize_t result = 0;struct sockaddr_in server_addr;struct sockaddr_in client_ addr;//Create datagram Socket SERVER_SOCKFD = socket (af_inet, SOCK_DGRAM, 0);//Set listening port, ipserver_addr.sin_family = Af_inet;server_ ADDR.SIN_ADDR.S_ADDR = htonl (inaddr_any); server_addr.sin_port = Htons (9739); server_len = sizeof (SERVER_ADDR);// Bind (name) socket bind (SERVER_SOCKFD, (struct sockaddr *) &server_addr, Server_len);//Ignore information about the child process stopping or exiting signal (SIGCHLD, Sig_ IGN); while (1) {//Receive data, use CLIENT_ADDR to store the IP port of the data source program result = Recvfrom (server_sockfd, buffer, sizeof (buffer), 0, (struct so CKADDR *) &client_addr, &client_len); if (fork () = = 0) {//Use subprocess to process data buffer[0] + = ' A '-' a '; sleep (1);//Send processed data send To (server_sockfd, buffer, sizeof (buffer), 0, (struct SockaDDR *) &AMP;CLIENT_ADDR, Client_len);p rintf ("%c\n", buffer[0]);//Note that you must close the child process, or the program will run abnormally exit (0);}} Close socket Close (SERVER_SOCKFD);}

The source code for SOCKCLIENT2.C is as follows:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h>int Main (int argc, char **argv) {struct sockaddr_in server_addr;socklen_t Server_len = 0;int SOCKFD =-1 ; char c = ' A ';//Take the first character of the first argument if (argc > 1) {c = argv[1][0];} Create datagram Socket SOCKFD = socket (af_inet, SOCK_DGRAM, 0);//Set server IP, port server_addr.sin_family = Af_inet;server_addr.sin_ ADDR.S_ADDR = inet_addr ("127.0.0.1"); Server_addr.sin_port = Htons (9739); server_len = sizeof (SERVER_ADDR);// Send data to the server SendTo (SOCKFD, &c, sizeof (char), 0,   (struct sockaddr *) &server_addr, Server_len);// After receiving the server processing data sent over, because do not care about the data source, so the latter two parameters set to 0recvfrom (SOCKFD, &c, sizeof (char), 0, 0, 0);p rintf ("char from server =%c\n", c );//closing socket close (SOCKFD); exit (0);}

The results of the operation are as follows:

Run the server program first, as follows:

Run three more clients: the following:

In this example, we started a server program and three client programs, and from the results of the operation, all the requests that the client sent to the server program were processed, that is, the uppercase letters were converted to lowercase. The Recvfrom () call is a blocking call that is returned only when the data is received.

the comparison between the datagram socket and the flow socket

1, from the use of convenience and efficiency in terms of

We can see that using datagram sockets is indeed simpler and faster than using a streaming socket.

Because a program that uses a streaming socket, the client needs to call Connect () to create a connection to the server program and needs to maintain the connection, the server program also needs to call listen () to create a queue to hold the unhandled request, and when the data arrives, The server also does not need to call accept () to take the connection and create a new socket descriptor to handle the request.

Take a look at the programs that use datagram sockets, where the server program is roughly the same as the system call used by the client, and the server program uses only one bind () call than the client program. A datagram socket-based program that only needs to use the SendTo () call to send information to the program that specifies the IP port, using the Recvfrom () call to receive information from the IP port to which it is pointing. Because it does not need to establish a connection, accept connections and so on, so save a lot of effort.

2, from the use of the occasion

We know that the flow socket is based on the TCP/IP protocol, which is a secure protocol that provides an orderly, reliable, bidirectional byte stream connection that sends data to ensure that it is not lost, duplicated, or ordered to arrive, and that there is a certain mechanism for resending the error. So it is more suitable for sending data files with large amount of information, or for files with high data integrity requirements, such as compressed files, video files, etc.

The datagram socket is implemented based on the UDP/IP protocol. It has a limit on the length of data that can be sent, the datagram is transmitted as a separate network message, it may be lost, copied, or garbled, and UDP is not a reliable protocol, but it is relatively high speed. Therefore, it is more suitable for sending some data that is more demanding for real-time, but not too high on security and integrity. such as we are familiar with the chat information, even if a little loss will not cause a big understanding of the problem.

Reference:

http://blog.csdn.net/ljianhui/article/details/10697935

Linux interprocess communication-datagram socket sockets (), bind (), sendto (), Recvfrom (), Close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.