Home > Back-end >  Why must I use default TcpClient to connect to server?
Why must I use default TcpClient to connect to server?

Time:12-11

Using the following code, my client fails to connect my server:

private static TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0));
private static IPEndPoint destinationEp = new IPEndPoint(IPAddress.Parse("192.168.0.100"), 1234);
//...
client.Connect(destinationEp);

Using TcpClient client = new TcpClient() instead will work.

In the original case, my understanding is that I am setting the local IP to the local machine, and using any available port as the local port to facilitate communication. My suspicion is that the server is trying to connect to the client using the IP "127.0.0.1", which wouldn't work, but I don't know this for sure.

Why do I have to use new TcpClient() instead of new TcpClient(myEndpoint) to successfully establish a server connection?

CodePudding user response:

See the docs:

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

Emphasis mine. You use that constructor only if you want to control the local part of the socket. See also the remainder of the docs:

You do not need to specify a local IP address and port number before connecting and communicating. If you create a TcpClient using any other constructor, the underlying service provider will assign the most appropriate local IP address and port number.

So your suspicion is correct. You're basically telling the network stack that you want your end of the socket to be bound to 127.0.0.1:0, which won't work for outbound connections.

  • Related