Skip to content

Instantly share code, notes, and snippets.

@marklap
Created August 12, 2021 21:42
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 marklap/3688f55609e708cc1fb8c0f7b28e3239 to your computer and use it in GitHub Desktop.
Save marklap/3688f55609e708cc1fb8c0f7b28e3239 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2021 Mark LaPerriere
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
################################################################################
"""
Simple UDP server that prints out messages it receives.
Requires: Python3.6+
"""
import atexit
import argparse
import socket
import sys
from typing import Any, Callable, Tuple
DEFAULT_BUFSIZE = 1024
def cli() -> argparse.Namespace:
parser = argparse.ArgumentParser('UDP Server - prints out data received')
parser.add_argument(dest='ip', help='ip address to listen on')
parser.add_argument(dest='port', type=int, help='UDP port to listen on')
return parser.parse_args()
def setup_socket(ip: str, port: int) -> socket.socket:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((ip, port))
atexit.register(sock.close)
return sock
def listen(sock: socket.socket, data_handler: Callable, bufsize: int = DEFAULT_BUFSIZE):
while True:
try:
data, addr = sock.recvfrom(bufsize)
except (SystemExit, KeyboardInterrupt):
break
data_handler(data, addr)
def print_addr_and_data(data: Any, addr: Tuple[str, int]):
print(f'[{addr}] {data}')
def main(args) -> int:
print(f'Listening for UDP messages on {args.ip}:{args.port}...\n')
sock = setup_socket(args.ip, args.port)
listen(sock, print_addr_and_data)
print('\nClosing up shop...')
return 0
if __name__ == '__main__':
sys.exit(main(cli()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment