HowTo: Kill TCP Connections in CLOSE_WAIT State

If you are seeing a large number of connections persisting in a CLOSE_WAIT state, it is probably an issue with the application itself.

Restarting it will clear the connections temporarily, but to find the real cause of the issue you would have to do the investigation.

If restarting of application is undesirable, you can manually kill all connections that are in the CLOSE_WAIT state.

Kill CLOSE_WAIT connections

Kill CLOSE_WAIT connections by IP

Kill TCP connections in CLOSE_WAIT state, established with the foreign IP address 192.168.0.100:

$ netstat -anp |\
  grep 192.168.0.100 |\
  grep CLOSE_WAIT |\
  awk \'{print $7}\' |\
  cut -d \/ -f1 |\
  grep -oE \"[[:digit:]]{1,}\" |\
  xargs kill

The same command in one line :

$ netstat -anp | grep 192.168.0.100 | grep CLOSE_WAIT | awk \'{print $7}\' | cut -d \/ -f1 | grep -oE \"[[:digit:]]{1,}\" | xargs kill

Kill CLOSE_WAIT connections by Port

Kill TCP connections in CLOSE_WAIT state on port 80:

$ netstat -anp |\
  grep \':80 \' |\
  grep CLOSE_WAIT |\
  awk \'{print $7}\' |\
  cut -d \/ -f1 |\
  grep -oE \"[[:digit:]]{1,}\" |\
  xargs kill

The same command in one line:

$ netstat -anp | grep \':80 \' | grep CLOSE_WAIT | awk \'{print $7}\' | cut -d \/ -f1 | grep -oE \"[[:digit:]]{1,}\" | xargs kill

Kill CLOSE_WAIT connections by IP & Port

Kill TCP connections in CLOSE_WAIT, state established with foreign IP address 192.168.0.100 on port 80:

$ netstat -anp |\
  grep 192.168.0.100 |\
  grep \':80 \' |\
  grep CLOSE_WAIT |\
  awk \'{print $7}\' |\
  cut -d \/ -f1 |\
  grep -oE \"[[:digit:]]{1,}\" |\
  xargs kill

The same command in one line:

$ netstat -anp | grep 192.168.0.100 | grep \':80 \' | grep CLOSE_WAIT | awk \'{print $7}\' | cut -d \/ -f1 | grep -oE \"[[:digit:]]{1,}\" | xargs kill

Explanation

$ netstat -anp |\  # print network connections
  grep 192.168.0.100 |\  # established with IP 192.168.0.100
  grep \':80 \' |\  # established on port 80
  grep CLOSE_WAIT |\  # connections in CLOSE_WAIT state
  awk \'{print $7}\' |\  # print the 7th column
  cut -d \/ -f1 |\  # extract PIDs
  grep -oE \"[[:digit:]]{1,}\" |\  # extract PIDs
  xargs kill  # kill PIDs