How to Send UDP Messages in Python?

Problem Formulation: How to send and receive UDP messages in Python?

Background: The User Datagram Protocol (UDP) network layer allows you to send messages without providing deliverability guarantees. UDP is unreliable—massages may be lost or delivered out of order. But this makes UDP also fast, lightweight, and the protocol of choice for many streaming scenarios such as Netflix sending UDP messages to all watchers of a specific show.

We differentiate between sending and receiving UDP messages in Python. For the code presented in this tutorial, you don’t need to custom install any library as we only need the socket library which is already in Python’s standard library. 😎

Sending UDP Message

To send a UDP message to a program listening on a given IP address and PORT, overwrite the IP address, PORT, and MESSAGE and run the following code:

# SENDER

import socket

ip = "127.0.0.1"
port = 5000
msg = b"hello world"

print(f'Sending {msg} to {ip}:{port}')

sock = socket.socket(socket.AF_INET,
                     socket.SOCK_DGRAM)
sock.sendto(msg, (ip, port))

Now, you may ask: if send a message nobody is listening to, does it even exist? 😉

UDP Python

Receiving UDP Message

Here’s how you can create a receiver listening to the IP address and PORT and printing all received messages to the screen:

# RECEIVER

import socket

ip = "127.0.0.1"
port = 5000

sock = socket.socket(socket.AF_INET,
                     socket.SOCK_DGRAM)
sock.bind((ip, port))

print(f'Start listening to {ip}:{port}')

while True:
    data, addr = sock.recvfrom(1024) # buffer
    print(f"received message: {data}")

You can customize the processing of the messages as you desire.

Distributed systems engineers must be masters of at least one programming language. I know from personal experience as a distributed system doctoral researcher. If you want to boost your Python skills, consider joining my free email academy that teaches you everything you need to become a skilled Python pro! It’s free!

Sources