Recv Function Of Python Socket Class

Method Signature/Syntax:

  recv(bufsize[, flags])


    bufsize - No of bytes to receive.

flags - Supports values as specified the operating system. Multiple flags can be combined by doing a bitwise OR.


Return Value:

    Returns the received data as bytes object.



  • Unlike send(), the recv() function of Python's socket module can be used to receive data from both TCP and UDP sockets.
  • The example client and server programs given here for UDP, use recv() at both client and the server sides.

Example – UDP Server:

# ----- Example UDP based server program in Python that uses recv() function -----


import socket


# Define IP address and port number

ipAddress       = "";

portNumber      = 3131;


# Create a UDP socket

udpSvr = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);


# Bind the UDP socket to the IP address and the port number

udpSvr.bind((ipAddress, portNumber))


# Receive datagrams from clients forever

bufferSize = 1024;


# Receive incoming datagrams


    udpClientData = udpSvr.recvfrom(bufferSize);


    # Datagram from client

    datagramFromClient      = udpClientData[0];


    # Datagram from server

    datagramSourceAddress   = udpClientData[1] ;  



    udpSvr.sendto("Datagram from Server".encode(), datagramSourceAddress);


(b'Datagram from Client', ('', 50559))

(b'Datagram from Client', ('', 57225))

Example – UDP Client:

# ----- Example UDP client program in Python that uses recv() function -----

import socket


msg         = "Datagram from client";

ipAndPort   = ("", 3131);

udpClient   = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);


# Send a datagram to the UDP server

udpClient.sendto(msg.encode(), ipAndPort);


# Receive a reply from UDP server

datagramFromServer  = udpClient.recv(1024);


# Print the received datagram from server



Datagram from Server


Copyright 2019 ©