How to bind a range of local port for client socket

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to specify a range of outgoing port numbers (i.e., 20000-21000). Is
there any way to bind this range so that when system picks up a free port, it
will only pick one from this range? I know I can bind a specific port number
but I'd rather let the system pick up an available one from the specific
range.

Can someone tell me how to do that?

Thanks in advance,
 
Vuong,

Thanks, but the linked one is not using any port binding. It was just a
simple port scanning.
 
Franky,
If you can scan available ports from range, you can bind at these ports.
And obviously, you can choose the port is available for use

Best Regards,
Vuong
Tran Xuan
 
Those comments are copied all over the net and nobody added an answer.

Here is how i managed to do it today:

I first need to define a range for ports to be used and pick one randomly
private int RandomPort()
{
int min = 20000;
int max = 30000;
Random random = new Random();
return random.Next(min, max);
}
then use this port for local endpoint for the client:

IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Any, RandomPort());
before i connect just bind this endpoint
clientSocket.Bind(LocalEndPoint);

and then connect to server

Example:
clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
 
Back
Top