Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sockets

I am currently using this function call to create my tcpClient:

clientSocket = new TcpClient("localhost", clientPort);

But the clientPort is the server's port.

Is there a way for me to specify the client port using tcpClient?

Thanks

like image 590
alex Avatar asked May 19 '10 22:05

alex


1 Answers

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);
like image 165
dtb Avatar answered Oct 05 '22 09:10

dtb