TCP socket does not detect client initiated disconnect (CLOSE_WAIT)  
Author Message
Miha Vitorovic





PostPosted: .NET Framework Networking and Communication, TCP socket does not detect client initiated disconnect (CLOSE_WAIT) Top

Hi all,

I'm having some problem with a client server communication. The problem is, that the server does not seem to detect that the client has closed connection until it tries to send something to it.

The session is stuck in CLOSE_WAIT state, even though I have done everything I could find in the MSDN to detect the Disconnected state...

This is, what my Disconnected function looks like:

private static bool Connected(Socket c)
{
try
{
if (!s.Connected) return false;

if (!s.Poll(-1, SelectMode.SelectWrite)) return false;

bool BlockingState = s.Blocking;
s.Blocking = false;

SocketError errorCode = SocketError.Success;
s.Send(new byte[1], 0, 0, SocketFlags.None, out errorCode);
s.Blocking = BlockingState;
return ((errorCode == SocketError.WouldBlock) || (errorCode == SocketError.Success));
}
catch (SocketException e)
{
log.Log("Socket exception: (" + Enum.Format(e.SocketErrorCode.GetType(), e.SocketErrorCode, "G") + ") " + e.Message);
return false;
}
catch (Exception e)
{
log.Log("Unexpected exception: (" + e.GetType().ToString() + ") " + e.Message);
return false;
}
}

So, sending 0 data does not work, even though it was supposed to.

The Network Monitor shows that the client has actually sent a FIN packet but obviously the framework does not detect that:

80 14.797882 LOCAL CISCO 07AC19 TCP Control Bits: .A...F, len: 0, seq:4195613401-4195613402, ack: 197241706, win:65517, src: 2299 dst:20067 Client Server IP
81 14.798859 000BFDCA1A80 LOCAL TCP Control Bits: .A...., len: 0, seq: 197241706-197241706, ack:4195613402, win:64062, src:20067 dst: 2299 Server Client IP

So my question is: how do I detect that the socket is actually in the CLOSE_WAIT state the way netstat does I don't mind doing the low level stuff, jsut somebody please point me in the right direction.

Thanks and best regards, Miha Vitorovic



.NET Development32  
 
 
Miha Vitorovic





PostPosted: .NET Framework Networking and Communication, TCP socket does not detect client initiated disconnect (CLOSE_WAIT) Top

Well I did find the netstat equivalent, but I'd rather query for each connection separately, than get a list of all TCP connections. Hmm

public static void GetTcpConnections()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();

foreach (TcpConnectionInformation t in connections)
{
Console.Write("Local endpoint: {0} ",t.LocalEndPoint.Address);
Console.Write("Remote endpoint: {0} ",t.Remo****dPoint.Address);
Console.WriteLine("{0}",t.State);
}
}
Best, Miha Vitorovic