Hi Folks, Below is a vb.net function which will return back the next available port from a range of port number so that you can use the next available port to open up a socket or do whatever is required.
I was not trying to open up multiple clients on the same port number or anything mad like that. I just needed to figure out which port numbers where available for use and direct the client to use that port number. This was for use in a Citrix environment where multiple clients were attempting to open the same port from different user sessions; using the code below allow us to resolve the issue.
''' <summary>
''' Routine to get the next available port number from a range of port numbers
''' </summary>
Private Function GetPortNumberFromRange(ByVal startPort As Integer, ByVal endPort As Integer) As Integer
Dim ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
Dim tcpInfos = ipProperties.GetActiveTcpConnections()
Dim portRange = Linq.Enumerable.Range(startPort, endPort).ToList
For Each tcpInfo In tcpInfos
portRange.Remove(tcpInfo.LocalEndPoint.Port)
Next
If portRange.Count > 0 Then
Return portRange(0)
End If
End Function