Overview:
-
The sendmsg() function sends non-ancillary data from multiple buffers to a destination socket. It also sends ancillary data if any and the related information as one or more tuples.
-
The sendmsg() function sends data using TCP, UDP and Unix Domain Protocol.
-
While the sendmsg() sends non-ancillary data by concatenating the contents of multiple bytes like objects, the recvmsg() function sends non-ancillary data by returning a bytes object inside a tuple containing other related information.
-
TCP is a connection oriented protocol where data is streamed between two connected sockets. UDP is a connectionless protocol where data is sent as discrete messages between sockets. Unix domain protocol sends file descriptors across processes in the same machine without using the protocol stack overhead.
Example - Server using Unix domain socket:
The example uses Unix domain sockets and the socket interface to send a text message through non-ancillary data and file descriptors through ancillary data from the client process to the server process running in the same machine. In this mechanism the kernel takes care of providing the valid file descriptors to the other process. It works for processes running in the same machine. Socket instances are created with the adress family socket.AF_UNIX.
The send_fds() and recv_fds() methods of the Python socket class send and receive file descriptors using Unix domain sockets.
# Example Python server program that # Create Unix domain socket # Bind the server socket to a path # Listen for incoming connections while(True): fdList = None # List of file descriptors # The kernel recreated the file descriptors...just use them |
Output:
Unix domain socket listening... Message received at server... Non-ancillary message:Temperature data Contents of the file descriptor: File 1 contents: time temp(in degree Celsius) 00.00 23 01.00 22 02.00 22 03.00 19 04.00 17 05.00 18 06.00 19 07.00 19 08.00 23
File 2 contents: time temp(in degree Celsius) 00.00 23 01.00 22 02.00 22 03.00 19 04.00 17 05.00 18 06.00 19 07.00 19 08.00 23 |
Example - Client using Unix domain socket and sendmsg() method:
# Example Python program that sends file # Create two file descriptors and send them # Create a Unix domain socket # Connect to the server # Non-ancillary message for the sendmsg() function # Ancillary message for the sendmsg() function # Send nonAncilMsg + ancillaryMsg to the server |
Output:
Message sent to the server |