Skip to content

Instantly share code, notes, and snippets.

@kylemanna
Created April 10, 2020 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylemanna/fca9b1b6ce91aff1fccaa07bc49a6f10 to your computer and use it in GitHub Desktop.
Save kylemanna/fca9b1b6ce91aff1fccaa07bc49a6f10 to your computer and use it in GitHub Desktop.
# Run this tool and feed it stuff.
# $ python3 udp-test.py
#
# Emulate a remote client sending data:
# $ cat /dev/urandom | nc -u 127.0.0.1 7502
#
# Cancel netcat and try again, second attempt will fail because the source port
# likely changed (not guaranteed, but statistically likely)
#
import socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 ** 16)
udp_socket.bind(('127.0.0.1', 7502))
PACKET_SIZE_BYTES = 16
# Read address of first packet and only allow future data to come from that
_, addr = udp_socket.recvfrom(0)
udp_socket.connect(addr)
while True:
# Don't use recvfrom, we know who the source is because of connect()
packet = udp_socket.recv(PACKET_SIZE_BYTES)
print(packet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment