Check if something is listening at a port on a server using C#
IPAddress [] hostIPAddresses = Dns.GetHostAddresses(hostName);
IPAddress selectedIPAddress = null;
if (hostIPAddresses == null || hostIPAddresses.Length == 0) { return ListenerStatus.Unknown; }
for (int i = 0; i < hostIPAddresses.Length; i++)
{
if (hostIPAddresses[i].AddressFamily == AddressFamily.InterNetwork)
{
selectedIPAddress = hostIPAddresses[i];
break;
}
}
if (selectedIPAddress == null) { return ListenerStatus.Unknown; }
Socket socketInstance = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socketInstance.Connect(selectedIPAddress, port);
if (socketInstance.Connected == true)
{
//Port is in use and connection is successful
return ListenerStatus.Listening;
}
return ListenerStatus.NotListening;
}
catch (SocketException ex)
{
if (ex.ErrorCode == 10061)
{
//Port is unused and could not establish connection
return ListenerStatus.NotListening;
}
return ListenerStatus.Unknown;
}
finally
{
if (socketInstance != null)
{
socketInstance.Close();
}
}
IPAddress selectedIPAddress = null;
if (hostIPAddresses == null || hostIPAddresses.Length == 0) { return ListenerStatus.Unknown; }
for (int i = 0; i < hostIPAddresses.Length; i++)
{
if (hostIPAddresses[i].AddressFamily == AddressFamily.InterNetwork)
{
selectedIPAddress = hostIPAddresses[i];
break;
}
}
if (selectedIPAddress == null) { return ListenerStatus.Unknown; }
Socket socketInstance = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socketInstance.Connect(selectedIPAddress, port);
if (socketInstance.Connected == true)
{
//Port is in use and connection is successful
return ListenerStatus.Listening;
}
return ListenerStatus.NotListening;
}
catch (SocketException ex)
{
if (ex.ErrorCode == 10061)
{
//Port is unused and could not establish connection
return ListenerStatus.NotListening;
}
return ListenerStatus.Unknown;
}
finally
{
if (socketInstance != null)
{
socketInstance.Close();
}
}
Comments
Post a Comment