170

In my Python socket program, I sometimes need to interrupt it with Ctrl-C. When I do this, it does close the connection using socket.close().

However, when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended?

1

17 Answers 17

174

Yes, this is intended. Here you can read a detailed explanation. It is possible to override this behavior by setting the SO_REUSEADDR option on a socket. For example:

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Sign up to request clarification or add additional context in comments.

5 Comments

You need to import module called socket.
IMPORTANT NOTE: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) works, BUT you should use that right after you create the socket. It will not work after .bind()!
where do you set this? Inside python? bash?
@thistleknot No, in your code. For example: udp = socket.socket(socket.AF_INET, / socket.SOCK_DGRAM) / udp.bind((UDP_IP, UDP_PORT)) / udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) (/ is a new line)
How do you do this on BaseHTTPRequestHandler? I can't find an opening to set SO_REUSEADDR.
70
$ ps -fA | grep python
501 81211 12368   0  10:11PM ttys000    0:03.12  
python -m SimpleHTTPServer

$ kill 81211

3 Comments

Unfortunately, it doesn't always work. This was my immediate thought when I ran into this problem, but there is no python process to kill in my case.
@Kryten use Kill -9 81211
Do not use kill -9. It wouldn't work in this case anyway as the user stated that there is no python process to kill.
54

This happens because you trying to run service at the same port and there is an already running application. it can happen because your service is not stopped in the process stack. you just have to kill those processes.

There is no need to install anything here is the one line command to kill all running python processes.

for Linux based OS:

Bash:

kill -9 $(ps -A | grep python | awk '{print $1}')

Fish:

kill -9 (ps -A | grep python | awk '{print $1}')

3 Comments

The command for Bash worked, but it also shut down my spyder (python IDE).
Note that this kills instantly every running python process! It is better to first get the list of python processes and then kill with the id. Just in case you got important python processes running you dont wont to be killed.
What about simply killall python? Is that not available everywhere? Or does it behave differently?
28

If you use a TCPServer, UDPServer or their subclasses in the socketserver module, you can set this class variable (before instantiating a server):

socketserver.TCPServer.allow_reuse_address = True

(via SocketServer.ThreadingTCPServer - Cannot bind to address after program restart )

This causes the init (constructor) to:

 if self.allow_reuse_address:
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

2 Comments

where do you set this? Inside python? bash?
18

A simple solution that worked for me is to close the Terminal and restart it.

Comments

15

Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler):

kill -9 $(lsof -ti tcp:443)

Of course this is only for linux-like OS!

Comments

12

For Linux,

ps aux | grep python

This will show you the error. The process number (eg.35225) containing your python file is the error.

Now,

sudo kill -9 35225

This will kill the error process and your problem will be solved.

Comments

8

First of all find the python process ID using this command

ps -fA | grep python

You will get a pid number by naming of your python process on second column

Then kill the process using this command

kill -9 pid

Comments

4

Do nothing just wait for a couple of minutes and it will get resolved. It happens due to the slow termination of some processes, and that's why it's not even showing in the running processes list.

1 Comment

I think this is true, but it doesn't help to know this.
3

run the command

fuser -k (port_number_you_are _trying_to_access)/TCP

example for flask: fuser -k 5000/tcp

Also, remember this error arises when you interput by ctrl+z. so to terminate use ctrl+c

2 Comments

This doesn't quite work if the process that used that port is already dead :q
NOTE you need lowercase tcp instead of TCP!
2

I faced similar error at odoo server and resolved that with these simple following steps:

  1. Paste following code in terminal

    ps -fA | grep python

You will get a pid number. Now copy the pid number from second column of terminal output.

  1. Then write as below

    kill -9 pid

The terminal will restart and then the command

flask run

Will work fine! Thank you

Comments

1

I tried the following code to settle the issue:

sudo lsof -t -i tcp:8000 | xargs kill -9

Comments

1

Use the following command to determine which process is using the port (replace PORT with the actual port number your application is trying to use, e.g., 8000):

sudo lsof -i :PORT

Once you have the PID, terminate it using the kill command:

sudo kill -9 PID

You can do it using a single command as well

sudo kill -9 $(sudo lsof -t -i :PORT)

Comments

0

I had the same problem (Err98 Address already in use) on a Raspberry Pi running python for a EV charging manager for a Tesla Wall Connector. The software had previously been fine but it stopped interrogating the solar inverter one day and I spent days thinking it was something I'd done in python. Turns out the root cause was the Wifi modem assigning a new dynamic IP to the solar inverter as as result of introducing a new smart TV into my home. I changed the python code to reflect the new IP address that I found from the wifi modem and bingo, the issue was fixed.

Comments

0

The cleanest way to make the socket immediately reusable is to follow the recommendation to first shutdown the client end (socket) of a connection, and make sure the server's end shuts down last (through exception handling if needed).

This might well mean that the server end runs forever.

This is not a problem if that "forever" loop pauses execution, e.g. read from socket.

How you "break" that "forever" loop is up to you as server admin, as long as there are no clients (apart from obvious system level exceptions)

Comments

0

in Terminal

Check PID of program:

$ netstat -tulpn

# output:

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
                   
#...
udp        0      0 127.0.0.1:20001         0.0.0.0:*                           2859/python 

in this case port: 20001, so PID is 2859

terminate this port:

$ kill -9 2859

Comments

-3

sudo pkill -9 python

try this command

1 Comment

Despite this being technically a possible solution to the problem here, I don't think this is a good idea to simply kill all python processes. What if you have some other processes that need python to work properly? You would kill all of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.