Created
October 18, 2025 22:06
-
-
Save ernstki/e01f7c9716b3003177688a11b92dd982 to your computer and use it in GitHub Desktop.
Get me the next available local TCP port, given a start port
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
| import sys | |
| import socket | |
| import logging | |
| logging.getLogger().setLevel(logging.DEBUG) | |
| port = None | |
| startport = 8000 | |
| MAXTRIES = 10 | |
| for p in range(startport, startport + MAXTRIES): | |
| try: | |
| s = socket.socket() | |
| s.connect(('127.0.0.1', p)) | |
| logging.debug("Port %s was taken, trying another", p) | |
| except ConnectionRefusedError: | |
| port = p | |
| break | |
| if not port: | |
| logging.debug("Couldn't find an available port") | |
| sys.exit(1) | |
| print(port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment