See this thread
https://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I wanted to get information if the port is available to set up a new TcpListener on it using c#. I have tried to use IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() and IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() methods, but there are more ports that I cannot start a tcp listener on. Most of them are reserved by windows, see https://superuser.com/questions/1486417/unable-to-start-kestrel-getting-an-attempt-was-made-to-access-a-socket-in-a-way or https://ardalis.com/attempt-made-to-access-socket/.
but there are also some that are not in use, not reserved and we still cannot start TcpListener on them, in my case:
Second solution that I have tried was trying to start a TcpListener and see if it will throw an exception, sth like:
static bool CanStartServer(int port)
{
var ip = IPAddress.Any;
var tcpServer = new TcpListener(ip, port);
try
{
tcpServer.Start();
}
catch (SocketException e)
{
return false;
}
tcpServer.Stop();
ip = IPAddress.IPv6Any;
tcpServer = new TcpListener(ip, port);
try
{
tcpServer.Start();
}
catch (SocketException e)
{
return false;
}
tcpServer.Stop();
return true;
}
but there are some cases when it starts a tcp server on already taken port and ip address, eg I can start tcpListener on port 6500 and ip 0.0.0.0, but I have already had a server:
Can you please explain it to me and tell me how to get all information I need to know which port can I use?