Check if a port is open or closed?

Are you searching article for solution of your trouble shouting when Check if a port is open or closed ?

The following code creates a socket to the given host and port number, and tries to establish a connection with it. Based on this, we could find whether the port is in use(Closed) or not in use(Open).

string hostname = "server1";
int portno = 9081;
IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];
System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
sock.Connect(ipa, portno);
if (sock.Connected == true) // Port is in use and connection is successful
MessageBox.Show("Port is Closed");

catch (System.Net.Sockets.SocketException ex)
if (ex.ErrorCode == 10061) // Port is unused and could not establish connection
MessageBox.Show("Port is Open!");


Author: Abhishek Arya22 Sep 2008 Member Level: Gold   Points : 0

Good one it works for me

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: