Is there a way to specify the local port to used in tcpClient?

The constructor overload that takes an IPEndPoint allows you to bind the internal Socket of the TcpClient to a specific port:

IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, clientPort);
TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
clientSocket.Connect(remoteHost, remotePort);

Leave a Comment