Created
February 10, 2024 16:57
-
-
Save ronakjain2012/988e1d0599ffda03c3598a4777bc792a to your computer and use it in GitHub Desktop.
Find available ports using python script from command line.
This file contains 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
import socket | |
import sys | |
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 | |
if __name__ == "__main__": | |
from_port = int(sys.argv[1]) | |
to_port = int(sys.argv[2]) | |
print(find_available_ports(from_port, to_port)) | |
# How to use | |
# python3 find_ports.py 1000 1050 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment