It seems that using socket.Close() for a tcp socket, doesn’t fully close the socket. In the following example I’m trying to connect to example.com at port 9999, which is not opened, and after a short-timeout, I’m trying to close the socket.
for (int i = 0; i < 200; i++)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.LingerState = new LingerOption(false, 0);
sock.BeginConnect("www.example.com", 9999, OnSocketConnected, sock);
System.Threading.Thread.Sleep(50);
sock.Close();
}
But when I take a look at netstat after the loop completes, I find that there are many half-opened sockets:
TCP israel-xp:6506 www.example.com:9999 SYN_SENT
TCP israel-xp:6507 www.example.com:9999 SYN_SENT
TCP israel-xp:6508 www.example.com:9999 SYN_SENT
TCP israel-xp:6509 www.example.com:9999 SYN_SENT
EDIT
.
Ok, some context was missing. I’m using beginconnect because I expect the socket connection to fail (9999 is not opened), and in my real code, I call the socket.Close() once a timer is set.
On OnSocketConnected I call EndConnect, which throws an exception (trying to call a method of a disposed object).
My goal is having a short timeout for the socket connection stage.
Any clue what I’m doing wrong?
Thanks!
It will close the .NET part of the socket. However according to the TCP specification the OS have to keep the lower level tidbits of the socket open for a certain amount of time in order to detect retransmission, and similar. In this particular case it’s likely keeping the socket around for a bit in order to detect a reply to the SYN packet sent so it can reply more sensibly and not mix up the reply with further packets sent.