Andre K
Andre K

Reputation: 347

Close TCP connection on Linux ungracefully

Is there a way to programmatically close a TCP connection in C/C++ ungracefully on Linux?

For testing, I would like to simulate the case when an endpoint is just powered down without transmitting any FIN and/or RST, and neither flushing any buffers.

Upvotes: 12

Views: 1661

Answers (4)

Mihaimyh
Mihaimyh

Reputation: 1410

You can use the close function from the unistd.h library to close the file descriptor associated with the socket. However, it is important to note that this method may not immediately terminate the connection, as the underlying TCP protocol has its own mechanisms for closing connections, and these mechanisms may take some time to complete.

Upvotes: 0

sancelot
sancelot

Reputation: 2053

I would prefer To act on the net driver irq processing. The Linux kernel provides a way to set the affinity of an IRQ to specific CPUs, so that the IRQ can only be processed by those CPUs. By setting the affinity of an IRQ to an empty set of CPUs, you can effectively disable the IRQ.

disable irqbalance daemon . then check which interrupts your nic driver uses .

cat /proc/interrupts

then forbids any cpu To process the nic irq : echo 0 > /proc/irq/N/smp_affinity

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126193

The easiest way to simulate the machine with the connection "going away" without notice is probably to block(drop) the incoming packets on the connection. A netfilter command like

iptables -A INPUT -p tcp --dport $PORT -j DROP

will do that -- replace $PORT with the connections local port number. The won't block outgoing packets (which may be an issue if you have keepalives or periodically send stuff.) You can do that with

iptables -A OUTPUT -p tcp --sport $PORT -j DROP

Be sure to remove these filtering rules when you're done, as otherwise they'll stick around and cause problems.

Upvotes: 2

Sanchke Dellowar
Sanchke Dellowar

Reputation: 108

If you're opening a socket via socket(AF_INET, SOCK_STREAM, 0); then its unpredictable to implement an ungraceful shutdown sense even killing the process will still give the kernel domain over closing the socket.

You can either externally block network access to that socket (ie ifdown, iptables), which you can call from your program. Or you'll have to implement custom TCP code using socket(AF_INET, SOCK_RAW, 0); so that the kernal doesn't try to close it gracefully (as it wouldn't know it's even a TCP socket).

Upvotes: 2

Related Questions