Python Programming
UDP Socket
Network Programming
Coding
Socket Programming

UDP socket programming using python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

UDP socket programming in Python is straightforward because the standard socket module exposes datagram sockets directly. The important part is understanding the tradeoff: UDP is fast and simple, but it does not guarantee delivery, ordering, or duplication control.

Create a Basic UDP Server

A UDP server binds to an address and waits for datagrams with recvfrom.

python
1import socket
2
3
4def run_server(host='127.0.0.1', port=9999):
5    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
6    sock.bind((host, port))
7    print(f'Listening on {host}:{port}')
8
9    while True:
10        data, address = sock.recvfrom(4096)
11        print(f'Received {data!r} from {address}')
12        sock.sendto(b'ack:' + data, address)
13
14
15if __name__ == '__main__':
16    run_server()

There is no listen or accept step because UDP is connectionless.

Create a Basic UDP Client

The client sends a datagram with sendto and optionally waits for a reply.

python
1import socket
2
3
4def run_client(message=b'hello', host='127.0.0.1', port=9999):
5    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
6    sock.settimeout(2)
7
8    sock.sendto(message, (host, port))
9    data, server = sock.recvfrom(4096)
10    print(f'Received {data!r} from {server}')
11    sock.close()
12
13
14if __name__ == '__main__':
15    run_client()

Because UDP does not guarantee a response, using a timeout is a good default.

Know What UDP Does Not Guarantee

Unlike TCP, UDP does not promise:

  • delivery
  • ordering
  • one-time delivery
  • retransmission

That means your application must tolerate dropped packets, out-of-order packets, or duplicates if those risks matter.

For small local-network discovery or telemetry workloads, that tradeoff may be perfectly acceptable. For reliable business transactions, it usually is not.

Add Timeouts and Basic Error Handling

A UDP client should normally set a timeout so the program does not block forever waiting for a response that may never arrive.

python
1try:
2    data, server = sock.recvfrom(4096)
3except socket.timeout:
4    print('No reply received in time')

That one addition makes test code and small tools much easier to debug.

Encode and Decode Messages Explicitly

If you are sending text, encode it before transmission and decode it on receipt.

python
message = 'ping'.encode('utf-8')
text = data.decode('utf-8')

Do not rely on implicit assumptions about payload type. UDP is just bytes on the wire.

Design the Protocol, Not Just the Socket Calls

The Python socket API is the easy part. The real design work is deciding how your application identifies message type, correlates replies, or retries important traffic.

Even a tiny protocol benefits from simple rules such as:

  • a message type prefix
  • a request ID
  • a timeout and retry policy

Without that, larger UDP programs become hard to reason about quickly.

For local development, running the server in one terminal and the client in another is the quickest way to see the packet flow and understand the connectionless behavior.

That hands-on check is useful because UDP problems are often protocol misunderstandings rather than Python syntax mistakes.

Even a tiny request-reply example benefits from an explicit timeout because silent packet loss is normal behavior in UDP, not an exceptional edge case.

Common Pitfalls

  • Expecting UDP to behave like TCP and guarantee delivery or ordering.
  • Forgetting to set a timeout and letting the client block forever.
  • Treating payloads as text everywhere even though sockets send raw bytes.
  • Building application logic without thinking about retries or duplicate packets.
  • Using UDP for workloads that really require reliable transport semantics.

Summary

  • Use socket.AF_INET and socket.SOCK_DGRAM for UDP in Python.
  • Servers use bind and recvfrom; clients use sendto and optionally recvfrom.
  • UDP is fast and simple because it omits reliability guarantees.
  • Timeouts and explicit encoding make small UDP tools much safer.
  • The real complexity lies in the application protocol layered on top.

Course illustration
Course illustration

All Rights Reserved.