Home > Software engineering >  How to check if a TCP connection is closed, accounting for IPV6?
How to check if a TCP connection is closed, accounting for IPV6?

Time:05-06

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?

CodePudding user response:

I ended up creating a check which "promotes" an endpoint to IPV6 if the other side is IPV6:

public static bool IsConnectionEstablished(this Socket socket)
{
    if (socket is null)
    {
        throw new ArgumentNullException(nameof(socket));
    }

    if (!socket.Connected) return false;

    var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    var tcpConnections = ipProperties.GetActiveTcpConnections()
        .Where(x => x.LocalEndPoint is IPEndPoint && x.RemoteEndPoint is IPEndPoint && x.LocalEndPoint != null && x.RemoteEndPoint != null)
        .Where(x => AreEndpointsEqual(x.LocalEndPoint, (IPEndPoint)socket.LocalEndPoint!) && AreEndpointsEqual(x.RemoteEndPoint, (IPEndPoint)socket.RemoteEndPoint!));

    var isConnected = false;

    if (tcpConnections != null && tcpConnections.Any())
    {
        TcpState stateOfConnection = tcpConnections.First().State;
        if (stateOfConnection == TcpState.Established)
        {
            isConnected = true;
        }
    }

    return isConnected;
}

public static bool AreEndpointsEqual(IPEndPoint left, IPEndPoint right)
{
    if (left.AddressFamily == AddressFamily.InterNetwork &&
        right.AddressFamily == AddressFamily.InterNetworkV6)
    {
        left = new IPEndPoint(left.Address.MapToIPv6(), left.Port);
    }

    if (left.AddressFamily == AddressFamily.InterNetworkV6 &&
        right.AddressFamily == AddressFamily.InterNetwork)
    {
        right = new IPEndPoint(right.Address.MapToIPv6(), right.Port);
    }

    return left.Equals(right);
}
  • Related