Originally from: http://rtomaszewski.blogspot.sk/2012/11/how-to-forcibly-kill-established-tcp.html
To "kill" a socket, you must send a TCP reset packet. To send it (and be accepted by the other side), you must know the actual TCP sequence number.
1) The already mentioned tcpkill
method learns the SEQ number by passively sniffing on the network and waiting for valid packets of this connection to arrive. Then it uses the learned SEQ number to send RSET packets to both sides. However if the connection is idle/hanged and no data flows, it won't do anything and will wait forever.
2) Another method uses perl script called killcx
(link to Sourceforge). This actively sends spoofed SYN packets and learns the SEQ number from the answer. It then sends RSET packets the same way as tcpkill
.
Alternatively approach (based on what you want to achieve) is to use gdb
debugger to attach to a process owning this socket/connection and issue close()
syscall on its behalf - as detailed in this answer.
If you want to deal only with hanged connections (the other side is dead), there are various timeouts (TCP keepalive for example), which should automatically close such connections if configured properly on the system.
ss
command is much easier and more general than the others.