Search code examples
c#socketstcp

C# asynchronous client socket problem - target machine actively refused it


I have a TCP server (written in Python) which accepts connections on the TCP socket, port 10200 on my local Windows machine (127.0.0.1). I have tested it with telnet and with some other applications and it seems to be working (no firewall issues, etc.).

The TCP Socket client (which I have issues with) is written in C#. It tries to asynchronously establish a TCP connection to the above socket. The code snippet is as follows:

public void Connect (string host, int port) {  
    try { 
        IPHostEntry ipHostInfo = Dns.GetHostEntry (host);
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);

        state.socket = new Socket (ipAddress.AddressFamily, 
                                   SocketType.Stream,
                                   ProtocolType.Tcp);
        state.socket.ReceiveTimeout = TcpState.RecvTimeout;

        state.socket.BeginConnect (remoteEP,
                new AsyncCallback (ConnectCallback), state);
    } catch (Exception e) {
        Debug.Log (e.ToString ());
        Disconnect ();
    }
}

// ...

private void ConnectCallback (IAsyncResult ar) {
    try {
 
        TcpState state = (TcpState) ar.AsyncState;

        state.socket.EndConnect (ar);
        // Here throws:
        // System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it.
        // ...
}

where state is a state object for receiving data from remote device, defined as a private member of the encapsulating class.

In Wireshark I see that the conversation was incomplete (flag 37):

enter image description here

What could cause such issues? If I run this code under Linux (C# is for Unity app) I don'


Solution

  • It's unclear what you were passing in for host, but if you want a loopback connection you don't need these three lines, and they wouldn't have worked if you were passing an IP address.

    IPHostEntry ipHostInfo = Dns.GetHostEntry (host);
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);
    

    Instead just use IPAddress.Loopback

    var remoteEP = new IPEndPoint(IPAddress.Loopback, port);
    

    As a side note, i strongly suggest you move to using async await, which is much easier to manage than the old Begin End style.