Been back and forth on this recently. Trying to attach a SSH tunnel from a localhost port on my machine to an internal port on the other side of an Internet accessible SSH server using Putty. Putty does not check if the port is available. Before I open the Putty connection, I would like to verify the port is free.
It works fine if the port is available, but I need a sure fire way to guarantee the port is not open at the time I check it in my code. I have used various methods with bad results. I am currently using the following code:
bool IsBusy(int port)
{
IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endpoints = ipGP.GetActiveTcpListeners();
if (endpoints == null || endpoints.Length == 0) return false;
for (int i = 0; i < endpoints.Length; i++)
if (endpoints[i].Port == port)
return true;
return false;
}
I have uTorrent installed on the computer. When I attempt to use port 3390, it fails because uTorrent is listening on that port via TCP. Is there a way to ensure TCP is not in use at all on a given port?