Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPAddress.Any Fail

). I got into a bit of issues today with the TcpListener. Things are strange. Initially, I used the new TcpListener(port) constructor, but that has been marked as obsolete. So I dropped it and used this instead:

   IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
   IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, ServerPort);
   TcpListener tcpServer = new TcpListener(ipLocalEndPoint);

   _TCPClient = tcpServer.AcceptTcpClient();
   GotClient();

I do that in a thread, of course, so that it doesn't lock the application. Now, what happens there, is that even though the ipAddress is correct, the server NEVER accepts ANY incoming connection.

HOWEVER, changing to new IPEndPoint(IPAddress.Any, ServerPort) seems to do the trick! Which is silly in 2 ways:

  1. 2 hours ago, IPAddress.Any returned 192.168.1.102 which is my correct local IP. This is the same IP which was in ipAddress! But with ipAddress it didn't work, while with IPAddress.Any it worked (that is, it successfully accepted connections from my client).

  2. Right now: IPAddress.Any returns 0.0.0.0 (!?) while the ipAddress variable continues to be assigned my correct IP (192.168.1.102). The result? My client still cannot connect if using ipAddres, but connects when using IPAddress.Any, even though it is 0.0.0.0.

I'm totally puzzled by this... Any thoughts?

I currently have this in Form_HandleCreated but it was acting weird when I had it in the Form's constructor as well.

LATER EDIT: I think I'm wrong about IPAddress.Any returning 192.168.1.102. I probably printed out something else, as many of you have indicated 0.0.0.0 is what .Any should return. Sorry ::- D.

like image 757
Axonn Avatar asked Jul 02 '26 06:07

Axonn


1 Answers

IPAddress.Any should return 0.0.0.0, that is normal. Are you actually sure it returned something else initially?

As for why you couldn't connect before, if you were listening on 192.168.1.102, and tried to connect to 127.0.0.1 (localhost), then it wouldn't work. You need to listen on 127.0.0.1 if you want to connect to that IP address.

Essentially, you must listen on the IP address you are attempting to connect to. Listening on 0.0.0.0 means, "listen on all available IP addresses". Remember, 127.0.0.1 (localhost) is not a synonym for "my local network IP".

like image 53
Mark Avatar answered Jul 03 '26 20:07

Mark