#!/usr/bin/env python3 """Serveur DHCPv4 minimaliste sans dépendance externe pour l'interface usb0 de la Radxa Zero 3W. Distribue automatiquement 192.168.1.10/24 (sans passerelle par défaut ni DNS) afin que la Galaxy Tab S8 Ultra (Android One UI) et le Steam Frame (SteamOS/Linux) montent la liaison USB-C Ethernet en plug-and-play dès le branchement, sans détourner le Wi-Fi/5G. """ import logging import os import socket import struct import sys import time IFACE = os.environ.get("DHCP_IFACE", "usb0") SERVER_IP = os.environ.get("DHCP_SERVER_IP", "192.168.1.1") OFFER_IP = os.environ.get("DHCP_OFFER_IP", "192.168.1.10") SUBNET_MASK = "255.255.255.0" BROADCAST_IP = "192.168.1.255" LEASE_SECONDS = 43200 # 12 h DHCP_MAGIC_COOKIE = b"\x63\x82\x53\x63" DHCPDISCOVER = 1 DHCPOFFER = 2 DHCPREQUEST = 3 DHCPACK = 5 DHCPINFORM = 8 logging.basicConfig( level=logging.INFO, format="%(asctime)s [usb0-dhcp] %(levelname)s: %(message)s", ) def parse_options(data: bytes) -> dict: opts = {} i = 0 n = len(data) while i < n: code = data[i] i += 1 if code == 0: # Pad continue if code == 255: # End break if i >= n: break length = data[i] i += 1 if i + length > n: break opts[code] = data[i : i + length] i += length return opts def build_dhcp_reply( req: bytes, msg_type: int, offer_ip: str, server_ip: str, ) -> bytes: xid = req[4:8] flags = req[10:12] ciaddr = req[12:16] chaddr = req[28:44] yiaddr = b"\x00\x00\x00\x00" if msg_type == DHCPACK and req[236:240] == DHCP_MAGIC_COOKIE and parse_options(req[240:]).get(53) == bytes([DHCPINFORM]) else socket.inet_aton(offer_ip) siaddr = socket.inet_aton(server_ip) header = bytearray(236) header[0] = 2 # BOOTREPLY header[1] = 1 # Ethernet header[2] = 6 # MAC len header[3] = 0 # Hops header[4:8] = xid header[8:10] = b"\x00\x00" # secs header[10:12] = flags header[12:16] = ciaddr if msg_type == DHCPACK else b"\x00\x00\x00\x00" header[16:20] = yiaddr header[20:24] = siaddr header[24:28] = b"\x00\x00\x00\x00" # giaddr header[28:44] = chaddr # Options DHCP : volontairement SANS option 3 (Router) ni option 6 (DNS) # pour ne pas casser la route Internet Wi-Fi/5G de la tablette Android ou du Steam Frame. opts = bytearray() opts += bytes([53, 1, msg_type]) # DHCP Message Type opts += bytes([54, 4]) + socket.inet_aton(server_ip) # Server Identifier opts += bytes([51, 4]) + struct.pack("!I", LEASE_SECONDS) # Lease Time opts += bytes([58, 4]) + struct.pack("!I", LEASE_SECONDS // 2) # Renewal (T1) opts += bytes([59, 4]) + struct.pack("!I", (LEASE_SECONDS * 7) // 8) # Rebinding (T2) opts += bytes([1, 4]) + socket.inet_aton(SUBNET_MASK) # Subnet Mask opts += bytes([28, 4]) + socket.inet_aton(BROADCAST_IP) # Broadcast Address opts += bytes([255]) # End return bytes(header) + DHCP_MAGIC_COOKIE + bytes(opts) def open_dhcp_socket(iface: str) -> socket.socket: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # SO_BINDTODEVICE = 25 sur Linux (évite de répondre sur wlan0/eth0) sock.setsockopt(socket.SOL_SOCKET, 25, iface.encode("utf-8") + b"\x00") sock.bind(("", 67)) sock.settimeout(2.0) return sock def main() -> int: logging.info( "Démarrage DHCP usb0 : iface=%s server=%s offer=%s (sans passerelle ni DNS)", IFACE, SERVER_IP, OFFER_IP, ) while True: sock = None try: sock = open_dhcp_socket(IFACE) logging.info("En écoute UDP :67 sur %s", IFACE) while True: try: data, _addr = sock.recvfrom(1500) except socket.timeout: continue if len(data) < 240 or data[0] != 1 or data[236:240] != DHCP_MAGIC_COOKIE: continue opts = parse_options(data[240:]) msg_type_raw = opts.get(53) if not msg_type_raw: continue msg_type = msg_type_raw[0] mac = ":".join(f"{b:02x}" for b in data[28:34]) if msg_type == DHCPDISCOVER: reply = build_dhcp_reply(data, DHCPOFFER, OFFER_IP, SERVER_IP) sock.sendto(reply, ("255.255.255.255", 68)) logging.info("DISCOVER de %s -> OFFER %s", mac, OFFER_IP) elif msg_type == DHCPREQUEST: reply = build_dhcp_reply(data, DHCPACK, OFFER_IP, SERVER_IP) sock.sendto(reply, ("255.255.255.255", 68)) logging.info("REQUEST de %s -> ACK %s", mac, OFFER_IP) elif msg_type == DHCPINFORM: reply = build_dhcp_reply(data, DHCPACK, OFFER_IP, SERVER_IP) sock.sendto(reply, ("255.255.255.255", 68)) logging.info("INFORM de %s -> ACK", mac) except OSError as exc: logging.warning("Interface %s indisponible (%s), nouvel essai dans 2s...", IFACE, exc) time.sleep(2.0) finally: if sock is not None: try: sock.close() except OSError: pass if __name__ == "__main__": sys.exit(main())