Datagram in Python

User Datagram Protocol (UDP) is a connectionless protocol that allows data transmission between network endpoints without establishing a persistent connection. In UDP communication, data is sent as datagrams ? independent packets that contain both the message and addressing information. The sender transmits packets without tracking delivery status, making UDP faster but less reliable than TCP.

Understanding UDP Communication

UDP communication requires two main components:

  • IP Address: Identifies the target machine on the network
  • Port Number: Specifies which application should receive the data

Python's socket module provides the necessary tools to implement UDP communication through datagram sockets.

Creating a UDP Sender

The sender program creates a UDP socket and transmits data to a specific IP address and port ?

import socket

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

print("Sent Message:", MESSAGE)

# Create UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
s.close()
Sent Message: Hello UDP!

Creating a UDP Receiver

The receiver program binds to a specific IP and port, then listens for incoming datagrams. The buffer size determines the maximum bytes that can be received in a single operation ?

import socket

UDP_IP = "localhost"
UDP_PORT = 5050

# Create and bind UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((UDP_IP, UDP_PORT))

print(f"UDP receiver listening on {UDP_IP}:{UDP_PORT}")

while True:
    # Buffer size is 1024 bytes
    data, addr = s.recvfrom(1024)
    print(f"Received message from {addr}: {data.decode('utf-8')}")
    
    # Break after receiving one message (for demo purposes)
    break

s.close()
UDP receiver listening on localhost:5050
Received message from ('127.0.0.1', 54321): Hello UDP!

Key UDP Socket Methods

Method Purpose Usage
socket.socket(AF_INET, SOCK_DGRAM) Create UDP socket Both sender and receiver
sendto(data, address) Send datagram to specific address Sender only
bind(address) Bind socket to IP and port Receiver only
recvfrom(buffer_size) Receive datagram and sender address Receiver only

Complete UDP Chat Example

Here's a practical example showing bidirectional UDP communication ?

import socket
import threading

def udp_receiver(ip, port):
    """Receive UDP messages"""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((ip, port))
    
    while True:
        try:
            data, addr = s.recvfrom(1024)
            print(f"Received: {data.decode('utf-8')} from {addr}")
        except:
            break
    s.close()

def udp_sender(target_ip, target_port, message):
    """Send UDP message"""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.sendto(bytes(message, "utf-8"), (target_ip, target_port))
    s.close()

# Start receiver in background
receiver_thread = threading.Thread(target=udp_receiver, args=("localhost", 5050))
receiver_thread.daemon = True
receiver_thread.start()

# Send messages
udp_sender("localhost", 5050, "Hello from Python!")
udp_sender("localhost", 5050, "UDP is connectionless!")

Conclusion

UDP datagrams provide fast, connectionless communication ideal for real-time applications where speed matters more than guaranteed delivery. Use sendto() for sending and recvfrom() for receiving datagrams in Python's socket module.

Updated on: 2026-03-15T17:06:56+05:30

670 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements