Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to "unbind" socket after binding free socket?

Tags:

python

sockets

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()
like image 947
PythonMan Avatar asked Oct 17 '22 00:10

PythonMan


1 Answers

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.

like image 67
taz Avatar answered Oct 19 '22 22:10

taz