sendto() function of python socket class

The sendto() function sends data in bytes form from an UDP socket to another UDP socket. The communication is between a client and a server in either direction. The python examples use sendto() in an UDP server and an UDP client.

socket Updated 28 Jun 2019 2 min read

Method Signature/Syntax

sendto(bytes, flags, address)

Parameters

bytes - The data to be sent in bytes format. If the data is in string format, str.encode() method can be used to convert the strings to bytes.

flags - As supported by the operating system, multiple values can be combined using bitwise OR. This optional parameter has a default value of 0.

address - A tuple consisting of IP address and port number.

Return Value

Returns the number of bytes sent.

Overview

  • The method sendto() of the Python's socket class, is used to send datagrams to a UDP socket.
  • The communication could be from either side. It could be from client to server or from the server to client.
  • For sendto() to be used, the socket should not be in already connected state.

Example – UDP server that uses sendto() function

python
# ----- An UDP server in Python that receives temperature values from clients-----

import socket

import datetime

# Define the IP address and the Port Number

ip      = "127.0.0.1";

port    = 7070;

listeningAddress = (ip, port);

# Create a datagram based server socket that uses IPv4 addressing scheme

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

datagramSocket.bind(listeningAddress);

while(True):

    tempVal, sourceAddress = datagramSocket.recvfrom(128);

    print("Temperature at %s is %s"%(sourceAddress, tempVal.decode()));

    response = "Received at: %s"%datetime.datetime.now();

    datagramSocket.sendto(response.encode(), sourceAddress);

Output

Output
Temperature at ('127.0.0.1', 64164) is 61.65

Temperature at ('127.0.0.1', 56309) is 61.66

Example – UDP client that uses sendto() function

python
# ----- An UDP client in Python that sends temperature values to server-----

import socket

import random

# Get temperature

def getTemp():

    temp = random.uniform(60.0, 62.0);

    return temp;

# A tuple with server ip and port

serverAddress = ("127.0.0.1", 7070);

# Create a datagram socket

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

# Get temperature

temperature = getTemp();

tempString  = "%.2f"%temperature;

# Socket is not in connected state yet...sendto() can be used

# Send temperature to the server

tempSensorSocket.sendto(tempString.encode(), ("127.0.0.1",7070));

# Read UDP server's response datagram

response = tempSensorSocket.recv(1024);

print(response);

Output

Output
b'Received at: 2019-06-28 23:12:49.262979'