recvmsg() function of python socket class

The recvmsg() function gets messages from connected sockets(TCP), unconnected sockets(UDP) and unix domain sockets. The message received is returned in a tuple consisting of data, ancillary data and related information.

socket Updated 15 Sep 2024 2 min read

Overview

  • The recvmsg() function receives messages through TCP sockets, UDP sockets and Unix domain sockets.
  • The recvmsg() function returns a tuple consisting of data received from the socket, ancillary data(i.e., control information), flags associated with the data and the address of the sender.
  • The Berkeley sockets implementation has the recvmsg() function receive data into multiple buffers. The Python implementation of recvmsg_into() function receives data into multiple buffers. The recvmsg() function returns the received message as a bytes object in a tuple along with other message related information.
  • The recvmsg() is versatile that it works with TCP sockets, UDP sockets and Unix domain sockets.

Example - Multi-threaded TCP server

python
# A Python TCP server program that waits

            # and serves a text string to the clients

            # connected to it using the socket methods

            # recvmsg() and sendmsg()

            import socket

            import threading

# Function that creates a server socket and

            # makes it to listen at a specific port for

            # incoming connections

            def serverInit():

                tcpServer   = socket.socket()

                ipAddress   = "127.0.0.1"

                portNum     = 34000

    # Bind to ip and port

                tcpServer.bind((ipAddress, portNum))

                print("TCP server listening at IP address {} port {}".format(ipAddress, portNum))

    # Start listening

                tcpServer.listen()

                return tcpServer

# Function that processes requests from clients

            # and sends responses - used as the target function of

            # threads spawned for each request

            def processRequest(con, address):

                while(True):

                    response = con.recvmsg(1024)

                    print(response[0])

        msgs = []

                    if(response[0] != b''):

                        msg1            = "Read client message\n"

                        msg1Bytes       = str.encode(msg1)

                        msgs.append(msg1Bytes)

            msg2            = "Connection being closed"

                        msg2Bytes       = str.encode(msg2)

                        msgs.append(msg2Bytes)

                        con.sendmsg(msgs)

            con.close()

                        print("Connection closed")

        break

# Start the server

            clientConthreads = []

            svr = serverInit()

            while(True):

                # Accept connections

                (cltConnection, cltAddress) = svr.accept()

    # Process requests

                cltConThread = threading.Thread(target=processRequest, args=(cltConnection, cltAddress))

                cltConThread.start()

                clientConthreads.append(cltConThread)

                for t in clientConthreads:

                    t.join()

Output

Output
TCP server listening at IP address 127.0.0.1 port 34000

b'GET / HTTP/1.1\r\nHost: localhost\r\n Connection: close\r\n\r\n'

Connection closed

Example - TCP client

python
# Example Python program that connects to a TCP server

            # and sends a request and prints the response of the server

            # onto the console

import socket

# Create a TCP socket

            sock = socket.socket()

            sock.connect(("localhost", 34000))

            print("Connected to the localhost")

httpGet     = "GET / HTTP/1.1\r\nHost: localhost\r\n Connection: close\r\n\r\n"

            reqBytes       = str.encode(httpGet)

            buffers = []

            buffers.append(reqBytes)

            sock.sendmsg(buffers)

while(True):

                response = sock.recvmsg(1024)

                print(response[0])

                if response[0] != b'':

                    sock.close()

                    break

print("Connection closed")

Output

Output
Connected to the localhost

b'Read client message\nConnection being closed'

Connection closed