Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket library thinks socket is open when it's not

I'm working with a bit of Python that looks like this:

HOST = '127.0.0.1'
PORT = 43434
single = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    single.bind((HOST, PORT))
except socket.error as e:
    # Print an error, exit.

While it's been functioning well in the past, we now get the error [Errno 98] Address already in use. The SIGINT handler closes the socket connection, so I'm not sure how it got in that state, but for now I'm just trying to fix it.

Both lsof and netstat say there's nothing using that port:

[$]> sudo netstat -an | grep 43434
[$]> sudo lsof -i :43434

TIME_WAIT is set to 60 seconds, according to /proc/sys/net/ipv4/tcp_fin_timeout, but the error occurs even hours after last run successfully.

I've tried (temporarily) setting REUSEADDR (via single.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)), but that appears to have no effect.

What in tarnation is going on? Will I ever be able to use this port again without having to reboot the machine?

like image 251
Xiong Chiamiov Avatar asked Oct 16 '13 20:10

Xiong Chiamiov


People also ask

Does Python automatically close socket?

Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a close if it's needed.

How do you stop a listening socket in Python?

To close the connection, break the while loop. Garbage collection will remove the thread or process but join will ensure none get left behind. Persistent sockets close when the user closes them or they timeout. Non-persistent, like static webpages will close after they've sent the information.

How do I check if a socket is alive in Python?

Use a try/except statement to test a socket connectionsocket. connect((ip_address, port_number)) to check if socket. socket is connected to ip_address at port_number . If this raises an error, the code in the except block is executed.


1 Answers

Try this:
tcpkill -i eth0 port 43434

like image 197
Ricky Wilson Avatar answered Oct 13 '22 03:10

Ricky Wilson