Search code examples
c#.netsocketstcptcpclient

SocketException when attempting to connect with TcpClient


When I try to create a new TcpClient I am getting a SocketException, here is my code:

public void TcpOpenConnection()
{
    // The next line is where the exception is occurring.
    tcpClient = new TcpClient(ipAddress, port);
    connected = true;
}

I have checked to make sure the port is open with netstat -a in cmd, and I even made another function to check if the port is open:

public static bool PortCheck(int port)
{
    bool portOpen = false;

    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    TcpConnectionInformation[] tcpConnInfo = ipGlobalProperties.GetActiveTcpConnections();

    foreach (var tcpConn in tcpConnInfo)
    {
        if (tcpConn.LocalEndPoint.Port == port)
        {
            portOpen = true;
            break;
        }
    }
    return portOpen;
}

which returns true. The exception that I am getting is a SocketException and it is saying the machine I am trying to connect to is actively refusing the connection. What could be the issue here? I have also tried other ports, with no luck.

If you need more info please ask, and I will gladly supply more.


Solution

  • The exception that I am getting is a SocketException and it is saying the machine I am trying to connect to is actively refusing the connection.

    This is likely an indication that the target host isn't listening on the port which could be caused by a number of reasons:

    • The router of the server's network is not correctly port-forwarded
    • The router's firewall / server's firewall is blocking the connections
    • The server and the client are not using the same port
    • The server is misconfigured

    The list goes on... but essentially, this error means that the server isn't allowing the connection.