Send Udp Packets In Python

Published on Aug. 18, 2022 | Tags: python networking udp TIL

Not that it's terribly hard to do, but is one of these useful things to know anb be able to source. Using the sockets library is triivally easy if you know the parameters you need to use (and it's very well documented).

import socket
from contextlib import contextmanager

IPADDR = "server-that-accepts-udp"
PORTNUM = 10000

def socket_context():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
sock.connect((IPADDR, PORTNUM))
yield sock

def send_udp_package(payload: bytes) -> None:
with socket_context() as sock:

send_udp_package(b"bytes message")

Of course, it's very low level so you'll need to know a bit about sockets to understand what's going on, but none the less, found it very useful.


Ferran Jovell