Search code examples
c#socketstcpclientconnection-refused

C# TCP Socket Client refuses connection


Here is my Server

When using multiple different port checking tools on the internet I get connections on my server, demonstrating that my ports are open

http://www.infobyip.com/tcpportchecker.php

http://www.yougetsignal.com/tools/open-ports/

http://ping.eu/port-chk/

http://ping.eu/port-chk/

Multiple successful connections

static void Main(string[] args)
{
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 10897);
    Console.WriteLine("Server Start");

    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    listener.Bind(localEndPoint);
    listener.Listen(10);
    while (true)
    {
        Console.WriteLine("Waiting for a connection...");
        Socket handler = listener.Accept();
        Console.WriteLine(handler.RemoteEndPoint);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
}

Here is my client code

 static void Main(string[] args)
 {
     IPEndPoint ip = new IPEndPoint(IPAddress.Parse("MY IP HERE"), 10897);
     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     server.Connect(ip);
 }

I get this error everytime, I have tried multiple different attempts from the client side using System.Net.Sockets.TcpClient and sockets and everytime I get connection refused so it appears to be some issue with my client since my server receives connections from port checkers Error

I have read through dozens of other socket topics but all of the issues have to do with the server and not the client, I no idea what is wrong can somebody help me?

EDIT: I can connect via localhost (127.0.0.1) but not from my public IP


Solution

  • The code works fine (the first two lines of your server do nothing). You have a firewall or routing issue.