Datagram in Python


Chunks of data move between the clients and servers using the User Datagram Protocol or UDP protocol. The two communicating endpoints need the IP address and port number to establish communication. One endpoint is known as the sender and the other is known as the receiver. In this protocol, the sender does not keep track of the sent packets and it is up to the receiver to accept or not all the packets.

Sender Program

The below python program uses the socket module to create the sender’s program. We declare variables for IP address and Port. Then add a message to it. The sendto() is used to combine the message with the IP address and port number.

Example

import socket

UDP_IP = "localhost"
UDP_PORT = 5050
MESSAGE = "Hello UDP! "

print ("Sent Message: ", MESSAGE)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

Output

Running the above code gives us the following result −

Sent Message: Hello UDP!

Receiver Program

Similarly, we create the receiver program which will receive the message sent by the sender program. The size of the message in the below program is restricted to 1024 bytes. The bind() function binds the IP and port to the data which is received.

Example

import socket

UDP_IP = "localhost"
UDP_PORT = 5050

s= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))

while True:
   # buffer size is 1024 bytes
   data, addr = sock.recvfrom(1024)
   print("Received message:", data)

Output

Running the above code gives us the following result −

Received message: Hello UDP!

Updated on: 17-Oct-2019

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements