How to abruptly disconnect a socket without closing it appropriately

Question:

I have a Python test program for testing features of another software component, let’s call the latter the component under test (COT).
The Python test program is connected to the COT via a persistent TCP connection.
The Python program is using the Python socket API for this.
Now in order to simulate a failure of the physical link, I’d like to have the Python program shut the socket down, but without disconnecting appropriately.
I.e. I don’t want anything to be sent on the TCP channel any more, including any TCP SYN/ACK/FIN. I just want the socket to go silent. It must not respond to the remote packets any more.

This is not as easy as it seems, since calling close on a socket will send TCP FIN packets to the remote end. (graceful disconnection).
So how can I kill the socket without sending any packets out?

I cannot shut down the Python program itself, because it needs to maintain other connections to other components.
For information, the socket runs in a separate thread. So I thought of abruptly killing the thread, but this is also not so easy. (Is there any way to kill a Thread?)

Any ideas?

Asked By: Scrontch

||

Answers:

You can’t do that from a userland process since in-kernel network stack still holds resources and state related to given TCP connection. Event if you kill your whole process the kernel is going to send a FIN to the other side since it knows what file descriptors your process had and will try to clean them up properly.

One way to get around this is to engage firewall software (on local or intermediate machine). Call a script that tells the firewall to drop all packets from/to given IP and port (that of course would need appropriate administrative privileges).

Answered By: Nikolai Fetissov

Contrary to Nikolai’s answer, there is indeed a way to reset the connection from userland such that an RST is sent and pending data discarded, rather than a FIN after all the pending data. However as it is more abused than used, I won’t publish it here. And I don’t know whether it can be done from Python. Setting one of the three possible SO_LINGER configurations and closing will do it. I won’t say more than that, and I will say that this technique should only be used for the purpose outlined in the question.

Answered By: user207421
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.