from .net_port_data import SERVICES from .net_port_is_port import is_port from .net_port_types import PortService, Protocol def port_service(port: int, protocol: Protocol) -> PortService: """The RFC 6335 range a port is in, and the IANA service registered on it for a protocol. A port with nothing in this registry's table has a null service: unassigned, or assigned but not common enough to ship here. """ if isinstance(port, bool) or not isinstance(port, int): raise TypeError("port must be an integer, received %r" % (port,)) if not is_port(port): raise ValueError("port must be 1 to 65535, received %d" % port) if protocol not in ("tcp", "udp"): raise ValueError('protocol must be tcp or udp, received "%s"' % (protocol,)) # RFC 6335 section 6: system 0-1023, user 1024-49151, dynamic 49152-65535. port_range = "system" if port <= 1023 else "user" if port <= 49151 else "dynamic" for row in SERVICES: if row.port == port and row.protocol == protocol: return PortService(port=port, protocol=protocol, range=port_range, service=row.service, description=row.description) return PortService(port=port, protocol=protocol, range=port_range, service=None, description=None)