Finding available ports within a given range requires checking if a specific port can be bound to or not. If we can bind to it, it means it’s available. One of the ways to achieve this is using Python’s socket module.
Here’s a function that checks the available ports within a range:
import socket
def find_available_ports(start_port, end_port):
available_ports = []
for port in range(start_port, end_port+1):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Set a timeout for trying to bind to a port
s.settimeout(1)
try:
s.bind(("0.0.0.0", port))
available_ports.append(port)
except socket.error:
pass
return available_ports
# Example usage:
start = 8000
end = 8100
print(find_available_ports(start, end))
We can make it a utility script by renaming it as “find_ports.py” and add the following:
import sys
if __name__ == "__main__":
from_port = int(sys.argv[1])
to_port = int(sys.argv[2])
print(find_available_ports(from_port, to_port))
Example:
$ python3 find_ports.py 1000 1050
[1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050]
The function uses a with statement to ensure that the socket is properly closed after it’s used.
The function attempts to bind to each port within the range. If binding is successful, it’s an available port.
Binding to 0.0.0.0 checks for availability on all network interfaces.
The settimeout(1) ensures that the binding doesn’t hang for too long. Adjust the timeout as needed.
Make sure you run the script with appropriate privileges, as some ports might be restricted and you might not get accurate results if you don’t have enough permissions. Also, note that other applications can occupy a port right after you’ve checked it, so use the results as a general guide and not as a definitive list of available ports.
Find the First Available Port
If you just want to get an available port, you can modify the script a bit to let it return once it found an available port. The following is a complete Python script to find available ports, and the function is added with an optional parameter specifying whether to return just a port.
import socket
import sys
def find_available_ports(start_port, end_port, only_one=False):
available_ports = []
for port in range(start_port, end_port+1):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Set a timeout for trying to bind to a port
s.settimeout(1)
try:
s.bind(("0.0.0.0", port))
available_ports.append(port)
if only_one:
return available_ports
except socket.error:
pass
return available_ports
if __name__ == "__main__":
from_port = int(sys.argv[1])
to_port = int(sys.argv[2])
print(find_available_ports(from_port, to_port))
–EOF (The Ultimate Computing & Technology Blog) —
559 wordsLast Post: Teaching Kids Programming - Count Servers that Communicate (Hash Map - Counter)
Next Post: Improve Multithreading Performance of Sqlite Database by WAL (Write Ahead Logging)