问题
I'm trying to make a basic client/server program, but when I start the TcpListener it gives me SocketException:The requested address is not valid in its context.
I actually have a method that returns my public IP, and it matches ipconfig results, so the IP address string below can't be the problem. Of course, the IP shown below isn't my real IP for security reasons. I opened the port below for general use.
Anyway, Not valid in context
is vague, so I'm not sure what that means.
Here's my code (for the TcpListener):
ServerIn = new TcpListener(IpAddress.Parse("100.100.100.100"), 8000);
ServerIn.Start();
Thanks in advance.
回答1:
The TcpListener can only be bound to a local IP Address of the computer that runs it. So the IP you're specifying isn't an IP of the local machine. Your public IP isn't the same IP as your local machine, especially if you're using some kind of NAT.
If I recall correctly, it's common to just do IPAddress.Any as your IP to initialise the listener.
回答2:
As written in MSDN about TcpListener
IPAddress- An IPAddress that represents the local IP address.
So it need to be a local IP address.
来源:https://stackoverflow.com/questions/17092647/socketexception-on-tcplistener-start