Zee
Zee

Reputation:

How to Abort a Socket in C#

I'm trying to abort a socket connection such that the client at the other end will get a "WSAECONNABORTED (10053) Software caused connection abort." error message when it polls the connection.

Close() and Shutdown() will disconnect gracefully. I don't want a graceful disconnection. I want to do an Abort so that the client senses something really went wrong.

Thanks,

EDIT: I'm coding a Server and I want to abort sockets to connecting clients

Upvotes: 9

Views: 10936

Answers (7)

Miles
Miles

Reputation: 526

To forcibly abort a connection you can do:

socket.Close(timeout: 0)

This will send a RST immediately.

Upvotes: 1

zahical
zahical

Reputation: 275

The underlying details, including when it is actually appropriate to forcibly abort a connection are described in great detail here (https://stackoverflow.com/a/13088864/1280848).

The C# way of doing this is:

socket.LingerState = new LingerOption(true, 0);
socket.Close();

That is, use SO_LINGER with TIME_WAIT = 0

Upvotes: 5

Jorge Mota
Jorge Mota

Reputation: 50

you can try to code all secondary sockets in another thread, and kill it when you want to crash connections.

Upvotes: -1

Zee
Zee

Reputation:

I've managed to simulate this situation:

To do a normal graceful disconnection:

you do:

socket.Shutdown(SocketShutdown.Both);
socket.Close();

However, to do an Abort, you do:

socket.Shutdown(SocketShutdown.Send);
socket.Close();

I think the difference is that the client will not receive any ACK packets and thinks the computer reset or something.

Upvotes: 2

HasaniH
HasaniH

Reputation: 8402

I don't think that it is possible to get the behavior you want with the .Net Socket implementation other than having the client send intermittent keep-alives. I've tried all sorts of things to get the behavior you described and ended up implementing keep-alive messages. If the sever calls Close() the client socket will get a connection aborted error the next time it attempts to send data.

Upvotes: 0

Kostas Konstantinidis
Kostas Konstantinidis

Reputation: 13707

try calling EndSend() or EndReceive() depending on the situation immediately followed by a Dispose()

Upvotes: -1

ChrisW
ChrisW

Reputation: 56113

What if you kill the process, and/or reboot the machine, and/or unplug the ethernet cable, without calling Close() and/or Shutdown()?

Upvotes: 1

Related Questions