Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No connection could be made because the target machine actively refused it - using Socket or TcpClient

Many people have this same problem, but everyone's implementation is different.

I need help with my implementation of it.

void sendUsingTcp() 
{
    try 
    {
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);
        sock.Connect(endPoint);
        // code past this never hits because the line above fails
    } 
    catch (SocketException err) 
    {
        MessageBox.Show(err.Message);
    }
}

I have also tried the TCP Client directly with the same error results:

void sendUsingTcp() 
{
    try 
    {
        using (TcpClient client = new TcpClient()) 
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);
            client.Connect(endPoint);
            // code past this never hits because the line above fails
        }
    } 
    catch (SocketException err) 
    {
        MessageBox.Show(err.Message);
    }
}

The IP Address of my PC is 172.16.11.144.

like image 423
jp2code Avatar asked Dec 07 '22 00:12

jp2code


2 Answers

For me it turned out, my Server was listening for incoming connections only from the same IP. I had to change the code for it to listen from any IP.

Before and Wrong:

IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);

After with problem fixed:

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8000);
like image 144
Rafael Emshoff Avatar answered Jan 24 '23 14:01

Rafael Emshoff


i) it's quite possible that port 8000 is used for something else. Pick another (large) number and see whether the same thing occurs ii) use the loopback address to connect to your own machine - IPAddress.Loopback

like image 23
Tom W Avatar answered Jan 24 '23 14:01

Tom W