Skip to content

Instantly share code, notes, and snippets.

@kylemanna
Created March 15, 2021 17:53
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/562be28c9b63a260b9a735f66f1bc414 to your computer and use it in GitHub Desktop.
Save kylemanna/562be28c9b63a260b9a735f66f1bc414 to your computer and use it in GitHub Desktop.
import socket
UDP_IP = '::'
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
connection_oriented = True
print(f"{connection_oriented=}")
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print(f"received message: {data} from {addr}")
if connection_oriented:
sock.connect(addr)
print(f"Issued connected command from {addr}, no new connections will appear...")
# Test code:
# $ echo hello $(date) | nc -u 127.0.0.1 5005
# $ echo hello $(date) | nc -u 127.0.0.1 5005
#
# If it's connection_oriented, only the first hello will work because it's bound to a soruce ip + port
# pair and re-running the command runs with a different source port.
# You'll need to restart the app or disconnect the socket to get data from a new connection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment