Kill orphaned CLOSE_WAIT TCP connections on Linux
Find and terminate TCP connections in CLOSE_WAIT state by port or remote IP, using netstat and lsof.
The CLOSE_WAIT state means the remote peer has closed the connection, but the local application has not yet closed its socket. Many connections stuck in this state usually point to an application that does not close its sockets. Killing processes only treats the symptom.
Kill CLOSE_WAIT connections on a port (lsof)
lsof -i :80 | grep CLOSE_WAIT | awk '{print $2}' | uniq | xargs kill
Kill CLOSE_WAIT connections to a remote IP (netstat)
netstat -anp | grep 192.0.2.10 | grep CLOSE_WAIT | awk '{print $7}' | cut -d '/' -f1 | grep -oE "[[:digit:]]{1,}" | xargs kill
Kill CLOSE_WAIT connections on a local port (netstat)
netstat -anp | grep ':80 ' | grep CLOSE_WAIT | awk '{print $7}' | cut -d '/' -f1 | grep -oE "[[:digit:]]{1,}" | xargs kill
Kill CLOSE_WAIT connections to a remote IP on a given port (netstat)
netstat -anp | grep 192.0.2.10 | grep ':80 ' | grep CLOSE_WAIT | awk '{print $7}' | cut -d '/' -f1 | grep -oE "[[:digit:]]{1,}" | xargs kill
How the pipeline works
| Step | Role |
|---|---|
netstat -anp |
Lists connections with the PID and program |
grep 192.0.2.10 |
Keeps connections to the remote IP |
grep ':80 ' |
Keeps connections on port 80 |
grep CLOSE_WAIT |
Keeps connections in the CLOSE_WAIT state |
awk '{print $7}' |
Extracts the PID/program column |
cut -d '/' -f1 |
Keeps the part before the slash, the PID |
grep -oE "[[:digit:]]{1,}" |
Extracts the digits of the PID |
xargs kill |
Sends the termination signal to the processes |
Notes
netstat -pshows the owning processes, which usually requires root privileges.- Killing a process also drops its other connections. Fixing the application that does not close its sockets is the real solution.
- The
192.0.2.xaddresses are placeholder values.