Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a single TCP connection in Linux?

Tags:

linux

tcp

I have a process that opens several tcp connections to several browsers on separate ports.

Using netsat the output is something like this :

tcp 0 0 server1.something:myprog client1.something:49987 ESTABLISHED
tcp 0 0 server1.something:myprog client1.something:65987 ESTABLISHED
tcp 0 0 server1.something:myprog client1.something:89987 ESTABLISHED

Now i would like to kill exactly one of the connections? How do i do it? (Since killing the process will kill all connections)

like image 983
outflanker Avatar asked Sep 17 '13 07:09

outflanker


People also ask

How do you kill an established TCP connection?

You can't kill a single connection of a process. But you could block it with iptables. So the connection can't provide or receive data and the client will run in a timeout. Save this answer.

How do I kill a TCP port?

For processes listening on a TCP or UDP port, the fuser command along with the -k (kill) option will terminate the related processes for you. Just specify the port type (TCP or UDP) and the port number in your command. For example, this would terminate processes utilizing TCP port 80.


2 Answers

Here are some options:

  • Attach with gdb and call close() on the fd. You can map from addr/port to inode number via /proc/net/tcp and from inode number to FD inside the process with ls -la /proc/$pid/fd.
  • Spoof a RST packet. You'll need to generate it locally and guess the SEQ number somehow.
  • Maybe setup an iptables rule to generate a RST on the next packet.
  • Write a kernel module.

There doesn't seem to be a well supported way to do this. It is likely that processes will crash if their FDs are unexpectedly closed anyway.

like image 80
cdleonard Avatar answered Sep 28 '22 19:09

cdleonard


On linux kernel >= 4.9 you can use the ss command from iproute2 with key -K

ss -K dst client1.something dport = 49987

the kernel have to be compiled with CONFIG_INET_DIAG_DESTROY option enabled.

like image 41
Pavel Avatar answered Sep 28 '22 18:09

Pavel