Mohamed Mansour's Personal Website
Articles
How to check if a port is binded or not
Posted on December 17, 2007, 3:32 pm EST
In this post, a very simple application, Remote Desktop Checker, will be given that checks if Microsoft Remote Desktop is working and active. Then I will explain how simple it is to check if a PORT is binded (Active) or not.
The application that I will be presenting here would be Remote Desktop. It is binded on port 3389, and we would like to check if it is active (binded) or not. The application looks like the following:
Download here: remotedesktopcheck.zip
How to check if a port is binded or not in C#
The code is basically the same in any language, you first bind the port, and see if an exception occurs. To do this in CSharp, you do it the following way.
CODE:
/// <summary>
/// Checks if a port which is binded locally is really binded
/// </summary>
/// <param name="port">Port that needs to be checked</param>
/// <returns></returns>
private bool CheckPortIfActive(int port)
{
try
{
// Create a TCP Stream on the current IPv4 Address
Socket myTestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Represent an IP End Point to the local computer with the RDP port
IPEndPoint ipConnect = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
// Bind that port to see if it will connect
myTestSocket.Bind(ipConnect);
// Cleanup
myTestSocket.Close();
return false;
}
catch (SocketException)
{
// Exception occured stating that the port is already binded, hence works fine!
return true;
}
}
That is it, this is how simple it is to check if a port is binded or not. The reason why I created this instead of doing "netstat -an" on command prompt, is because some people do not like command line and think it is too hard. They usually like a simple user interface. That is what I give to my friends that are NOT geeks, so that they could check quickly why their RDP isn't working.
I hope it helps some of you.

