I've used this code to check if a TCP connection is closed. However while using this code I noticed that it doesn't work with IPV6 addresses if the connection is using IPV4:
if (!socket.Connected) return false;
var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
var tcpConnections = ipProperties.GetActiveTcpConnections()
.Where(x => x.LocalEndPoint.Equals(socket.LocalEndPoint) && x.RemoteEndPoint.Equals(socket.RemoteEndPoint));
var isConnected = false;
if (tcpConnections != null && tcpConnections.Any())
{
TcpState stateOfConnection = tcpConnections.First().State;
if (stateOfConnection == TcpState.Established)
{
isConnected = true;
}
}
return isConnected;
While debugging the code in the linked answer I noticed that returns a list which includes the following endpoint:
{127.0.0.1:50503}
However the socket I'm testing against appears to be IPV6:
{[::ffff:127.0.0.1]:50503}
{127.0.0.1:50503} == {[::ffff:127.0.0.1]:50503}
returns false, so the check fails.
How can I test if an IPV4 address and IPV6 address refers to the same host?