Created
April 15, 2026 20:48
-
-
Save XertroV/fe8a220674380842d698d1766ef15b46 to your computer and use it in GitHub Desktop.
portpid — fast port-to-PID lookup by process name. Released under CC0 / Unlicense.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import glob | |
| import os | |
| import sys | |
| def hex_port(port: int) -> str: | |
| return f"{port:04X}" | |
| def get_socket_inodes(target_port: int) -> set: | |
| port_hex = hex_port(target_port) | |
| inodes = set() | |
| for path in ("/proc/net/tcp", "/proc/net/tcp6"): | |
| try: | |
| with open(path) as f: | |
| next(f) # skip header | |
| for line in f: | |
| parts = line.split() | |
| if len(parts) < 10: | |
| continue | |
| local = parts[1] | |
| # local format: 0100007F:22B8 or 0000000000000000FFFF00000100007F:22B8 | |
| if ":" in local: | |
| _, port_str = local.rsplit(":", 1) | |
| if port_str.upper() == port_hex: | |
| inodes.add(parts[9]) | |
| except FileNotFoundError: | |
| pass | |
| return inodes | |
| def pids_for_name(name: str): | |
| for comm_path in glob.glob("/proc/[0-9]*/comm"): | |
| try: | |
| with open(comm_path) as f: | |
| if f.read().strip() == name: | |
| pid = comm_path.split("/")[2] | |
| yield pid | |
| except (OSError, IOError): | |
| pass | |
| def pid_has_socket_inode(pid: str, inodes: set) -> bool: | |
| fd_dir = f"/proc/{pid}/fd" | |
| try: | |
| for fd in os.listdir(fd_dir): | |
| try: | |
| link = os.readlink(os.path.join(fd_dir, fd)) | |
| if link.startswith("socket:["): | |
| inode = link[8:-1] | |
| if inode in inodes: | |
| return True | |
| except (OSError, IOError): | |
| pass | |
| except (OSError, IOError): | |
| pass | |
| return False | |
| def main(): | |
| if len(sys.argv) != 3: | |
| print(f"Usage: {sys.argv[0]} <procname> <port>", file=sys.stderr) | |
| sys.exit(2) | |
| procname = sys.argv[1] | |
| try: | |
| port = int(sys.argv[2]) | |
| except ValueError: | |
| print("Port must be an integer", file=sys.stderr) | |
| sys.exit(2) | |
| inodes = get_socket_inodes(port) | |
| if not inodes: | |
| sys.exit(1) | |
| for pid in pids_for_name(procname): | |
| if pid_has_socket_inode(pid, inodes): | |
| print(pid) | |
| sys.exit(0) | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment