typestar

UDP datagrams in Python

Connectionless messaging with SOCK_DGRAM sockets.

import socket

listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
listener.bind(("127.0.0.1", 9999))
listener.settimeout(2)

sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sender.sendto(b"ping", ("127.0.0.1", 9999))

data, addr = listener.recvfrom(1024)
listener.sendto(b"pong", addr)

sender.close()
listener.close()

How it works

  1. sendto fires a datagram at an address.
  2. recvfrom returns the data and the sender.
  3. No handshake: packets just go.

The run, in numbers

Lines
14
Characters to type
337
Tokens
96
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 3 of 4 in Sockets & networking, step 8 of 41 in Domain tools.

← Previous Next →