71 lines
2.5 KiB
Python
Executable File
71 lines
2.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""portfree - find the first free port in a range.
|
|
Usage: portfree [START] [END] [--selftest]
|
|
Binds (not connects) to each port in the range in turn: a bind that
|
|
succeeds proves the port is free for a server to use, which is the
|
|
question you actually ask when picking a port for a new service.
|
|
Defaults: 8000-8100. Prints the first free port, or lists all free
|
|
ports with --all.
|
|
"""
|
|
import argparse
|
|
import socket
|
|
import sys
|
|
|
|
|
|
def is_free(port, host="0.0.0.0"):
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
try:
|
|
s.bind((host, port))
|
|
return True
|
|
except OSError:
|
|
return False
|
|
finally:
|
|
s.close()
|
|
|
|
|
|
def find_free(start, end, host="0.0.0.0"):
|
|
return [p for p in range(start, end + 1) if is_free(p, host)]
|
|
|
|
|
|
def selftest():
|
|
# Occupy one port, then check the finder skips it and finds a neighbour.
|
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
srv.bind(("127.0.0.1", 0))
|
|
busy = srv.getsockname()[1]
|
|
srv.listen(1)
|
|
try:
|
|
assert not is_free(busy, "127.0.0.1"), "occupied port reported free"
|
|
free = find_free(busy, busy + 2, "127.0.0.1")
|
|
assert busy not in free and len(free) >= 1, f"finder wrong: {free}"
|
|
print(f"selftest: port {busy} correctly busy; first free nearby is {free[0]} — OK")
|
|
return 0
|
|
finally:
|
|
srv.close()
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="portfree - find the first free port in a range")
|
|
ap.add_argument("start", nargs="?", type=int, default=8000, help="range start (default 8000)")
|
|
ap.add_argument("end", nargs="?", type=int, default=8100, help="range end (default 8100)")
|
|
ap.add_argument("--all", action="store_true", help="list every free port in the range")
|
|
ap.add_argument("--selftest", action="store_true", help="bind one port and verify the finder skips it")
|
|
args = ap.parse_args()
|
|
if args.selftest:
|
|
return selftest()
|
|
if args.start > args.end or not (0 < args.start < 65536) or not (0 < args.end < 65536):
|
|
ap.error("range must satisfy 0 < START <= END < 65536")
|
|
free = find_free(args.start, args.end)
|
|
if not free:
|
|
print(f"portfree: no free port in {args.start}-{args.end}")
|
|
return 1
|
|
if args.all:
|
|
print(f"free ports in {args.start}-{args.end}: {', '.join(map(str, free))}")
|
|
else:
|
|
print(f"first free port in {args.start}-{args.end}: {free[0]}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|