Consider the following code:
void Connect(IPAddress address, int port)
{
TcpListener listener = new TcpListener(address, port);
listener.Start();
TcpClient client= new TcpClient();
//The following line would actually block the caller, but ignore this fact ATM.
var conn= listener.AcceptTcpClient();
client.Connect(address,port);
var address = ((IPEndPoint)conn.Client.RemoteEndPoint).Address;
var port = ((IPEndPoint)conn.Client.RemoteEndPoint).Port;
}
The port number specified by the client does not correspond with the port number which I am able to obtain from the connection. The documentation for this property is pretty vague, and I could not find any similar question here or on MSDN. Does any one have an idea as to why this happens?
Help would be much appreciated. Eyal.
A TCP connection has an independent
(IP, port)
pair for both sides. You are connecting to(address, port)
but you are connecting from something else. The from IP and port are chosen automatically by the OS to be appropriate values.