UDP Socket Programming in Python

In this Python Socket Programming article we want to talk about UDP Socket Programming in Python, User Datagram Protocol (UDP) is transport layer protocol that is used to send and receive data packets between two networked devices. UDP is connectionless protocol which means that it does not establish dedicated end to end connection between the sender and receiver before transmitting data. instead UDP packets are sent as independent datagrams, and receiver does not have acknowledge about their receipt. and this makes UDP lightweight and efficient protocol, but also less reliable than TCP.

 

In this article we want to explore how to perform UDP socket programming in Python. we want to cover following topics:

  • Creating UDP socket
  • Sending data over UDP socket
  • Receiving data over UDP socket

 

 

Creating UDP socket in Python

For creating UDP socket in Python, we need to use the socket module. this is an example of how to create UDP socket, in this example we are using socket() function to create a socket object. first argument, socket.AF_INET specifies that we are creating an IPv4 socket. second argument, socket.SOCK_DGRAM specifies that we are creating UDP socket.

 

 

Sending data over UDP socket

For sending data over UDP socket, we need to use sendto() method. this is an example of how to send message over UDP socket, in this example, we are using sendto() method to send a message over the UDP socket. first argument of sendto() is the data we want to send, encoded as bytes. second argument is a tuple that specifies the IP address and port number of receiver.

 

 

Receiving data over UDP socket

For receiving data over UDP socket, we need to use recvfrom() method. this is an example of how to receive message over UDP socket, in this example we are using recvfrom() method to receive a message over the UDP socket. first argument to recvfrom() is the maximum number of bytes we want to receive. this method returns tuple containing received data and address of the sender. after that we decode the received data into a string and print it out along with the sender address.

 

 

 

This is the complete code for this article

 

 

Learn More

Leave a Comment