Find An Unused Random Local Port And Announce It On Redis

Redis
Python script
Redis port
Unused local port
Redis library
redis-py
finding an unused port
The article provides a detailed explanation of a Python script designed to find an unused local port and store it in Redis. It demonstrates the implementation using redis-py and the Python Redis library, making it easy for developers to understand and utilize this method for their projects.
Published

August 9, 2022


issues were found when launching apps on fixed ports.

maybe you should create this entry inside your lazero package? no need for uploading to pypi, just keep it under pyjom and leave a local install script there.

make sure all related services are going to launch after the redis_service.service target. on macos or windows this may vary.

allocate multiple unused ports at once or they may overlap.

abandon ports found on redis.

python to get unused port:

def getUnusedLocalhostPort():
"""
These were "Borrowed" from YCM.
See https://github.com/Valloric/YouCompleteMe
"""
sock = socket.socket()
# This tells the OS to give us any free port in the range [1024 - 65535]
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
return port

install redis-py:

pip install redis

python send port to redis:

import redis
r = redis.Redis(
host='hostname',
port=port,
password='password')
# open a connection to Redis
port = getUnusedLocalhostPort()
r.set('programPort', port)
value = r.get('programPort')
print(value)