Re: Finding an available port for a socket connection?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



andreas.baus@xxxxxxxxxxxxx wrote:
Mike Lowery schrieb:

Common practice is to use ports between 49152 and 65535. It's unlikely you'll
have a conflict in that range.
http://www.iana.org/assignments/port-numbers

It is acutally fairly likely there will be collisions if there are
several instances of my code running on the same machine under the same
- or at least very similar - configurations (this application is
supposed to run in a terminal server environment) which somehow need to
get along with each other.

I found this snippet of C#, that sounds like it does what you need.
Didn't write it myself, and I'm more of a VB guy myself, but it doesn't
look like it loops:

static int FindFreePort()
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
finally
{
socket.Close();
}
}

Don't see any way you could limit it to a particular range though
(plus, as is, it closes the socket, whereas you might want to keep the
socket open, to prevent race conditions with other instances of your
app)

Damien

.



Relevant Pages

  • Socket.ReceiveTimeout
    ... Socket socket = OpenDataSocket; ... The same code running on the PC for file transfers in the other direction ... Dim m_buffer As Byte ... Dim intBytesRead As Integer = 0 ...
    (microsoft.public.dotnet.framework.compactframework)
  • Re: Fine grain select locking.
    ... Here is an update that avoids the malloc per fd when there are no collisions. ... This unfortunately adds 64bytes to every socket in the system. ... Per-thread wait channel rather than global select wait channel. ... The unfortunate cost of this patch is that a descriptor per select fd must be allocated to track individual threads. ...
    (freebsd-arch)
  • Re: Finding an available port for a socket connection?
    ... Mike Lowery schrieb: ... have a conflict in that range. ... It is acutally fairly likely there will be collisions if there are ... several instances of my code running on the same machine under the same ...
    (microsoft.public.dotnet.framework)