tags: python net Another simple example of sockets. The `server.py` runs a server on port 1026. Opening a TCP socket to this port and reading it returns the hostname of the server. The `massclient.py` uses threads for each machine on a /24 subnet, and it gets the subnet using the `connect 8.8.8.8` trick to avoid getting the answer of localhost. (Interestingly [ChatGPT]() kept giving me code that returned the IP for localhost.) ## client.py ```py import socket from icecream import ic import sys import re args = sys.argv[1:] def make_local(n): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) x = s.getsockname()[0] s.close() xs = x.split(".") xs[-1] = str(n) return ".".join(xs) def do_arg(arg): if m := re.match(r"(\d+\.){3}\d+$",arg): ip = arg elif arg.isnumeric(): ip = make_local(arg) else: ip = arg s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip,1026)) data = s.recv(1024) print(ip,data.decode()) except ConnectionRefusedError: print(ip,"#Connection Refused") except TimeoutError: print(ip,"#Timeout") except Exception as e: ic(e) for arg in args: do_arg(arg) ``` ## massclient.py ```py import socket from icecream import ic import sys import re import threading args = sys.argv[1:] def make_local(n): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) x = s.getsockname()[0] s.close() xs = x.split(".") xs[-1] = str(n) return ".".join(xs) def do_arg(arg): if m := re.match(r"(\d+\.){3}\d+$",arg): ip = arg elif arg.isnumeric() or type(arg) is int: ip = make_local(arg) else: ip = arg s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) try: s.connect((ip,1026)) data = s.recv(1024) return data.decode() except TimeoutError: return None except ConnectionRefusedError: return None except Exception as e: ic(e) return None def get_name_task(idx): ip = make_local(idx) result = do_arg(ip) if result is not None: found[ip] = result found = {} threads = [] for i in range(2,254): thread = threading.Thread(target=get_name_task,args=(i,)) threads.append(thread) thread.start() for thread in threads: thread.join() for ip, name in found.items(): print(ip,name) ``` ## server.py ```py import socket import threading def hostname(): return socket.gethostname() def handle_client(client_socket): client_socket.send(hostname().encode()) client_socket.close() def main(): host = "0.0.0.0" port = 1026 try: server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((host,port)) server_socket.listen() while True: client_socket, client_address = server_socket.accept() client_thread = threading.Thread(target=handle_client, args=(client_socket,)) client_thread.start() except Exception as e: ic(2) finally: server_socket.close() if __name__ == main(): main() ```