How to Create a UDP Socket in Python

This guide provides a straightforward overview of creating and using a standard UDP (User Datagram Protocol) socket in Python. You will learn how to initialize a socket using Python’s built-in socket module, configure it for connectionless communication, and implement basic data transmission for both sending and receiving endpoints.

Initializing the UDP Socket

To work with network sockets in Python, use the standard library’s socket module. A standard UDP socket requires specifying the IPv4 address family (AF_INET) and the datagram socket type (SOCK_DGRAM).

import socket

# Create a standard UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

Receiving Data (UDP Server Example)

To receive incoming datagrams, bind the socket to an IP address and port number, then use the recvfrom() method.

import socket

# Define host and port
HOST = "127.0.0.1"
PORT = 8080

# Create and bind the socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((HOST, PORT))

print(f"UDP server listening on {HOST}:{PORT}...")

try:
    while True:
        # Buffer size of 1024 bytes
        data, client_address = server_socket.recvfrom(1024)
        print(
            f"Received message: {data.decode('utf-8')} from {client_address}"
        )
finally:
    server_socket.close()

Sending Data (UDP Client Example)

Because UDP is connectionless, you do not establish a connection via connect(). Instead, you transmit byte data directly to the destination address using sendto().

import socket

# Define target server address
TARGET_HOST = "127.0.0.1"
TARGET_PORT = 8080

# Create the socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Message must be encoded to bytes
message = "Hello, UDP Server!".encode("utf-8")

try:
    # Send datagram
    client_socket.sendto(message, (TARGET_HOST, TARGET_PORT))
    print(f"Sent message to {TARGET_HOST}:{TARGET_PORT}")
finally:
    client_socket.close()

Resource Cleanup

Always close your socket instances using socket.close() or by managing them within a with statement context manager to release the allocated network resources properly.