Completely Free .NET word API

Resources » Code Snippets » Network

Check if a port is open or closed?

Updated: Category: Network
Author: Member Level: GoldPoints: 10

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!");

Did you like this resource? Share it with your friends and show your love!

Responses to "Check if a port is open or closed?"
Author: Abhishek Arya  22 Sep 2008   Member Level: Gold   Points : 0
Good one it works for me


Post Comment:

  • 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)

    Type the numbers and letters shown on the left.

    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India