Reputation: 897
Do I have to explicitly release/unbind a socket so that it can be reused? I'm thinking of using close()
but I have seen some options like tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
. Do I have to use it or is close()
enough?
Is there any way to make sure that port is free for new bind?
TorPorts = {}
def port_setup(workers):
for worker in range(workers):
for i in range(2):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind(('', 0))
port = tcp.getsockname()[1]
print("{0} port {1}, tcp {2}".format(i,port,tcp))
if not TorPorts.has_key(worker):
TorPorts[worker] = {0:{},1:{}}
TorPorts[worker][i] = {"port":port,"tcp":tcp}
# do some programing
# close ports I s this enough?
for thread,ports in TorPorts[0].items():
tcp_port = ports["tcp"]
tcp_port.close()
Upvotes: 6
Views: 11664
Reputation: 76
It is better to use tcp_port.close()
And socket.SO_REUSEADDR
may fail in some scenarios. If that happens you cannot re-bind to same port until WAIT_TIME
gets completed.
Upvotes: 2