C# Tutorials and offshore development in India
Tutorials Resources Forum Reviews Communities Interview Jobs Projects Training Videos


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...


Birthday Greetings
Learn Windows 7: How to change the Window Explorer bar half color?   This article is about the changing the color of window explorer bar half color. Step to change the window explorer bar half color.



Resources » Code Snippets » Network »

Check if a port is open or closed?


Posted Date: 02 May 2007    Resource Type: Code Snippets    Category: Network
Author: Balamurali BalajiMember Level: Diamond    
Rating: 1 out of 5Points: 10



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];
try
{
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");
sock.Close();

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







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


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Retrieving TCP connections information
Previous Resource: Get MAC address of your system
Return to Resources
Post New Resource
Category: Network


Post resources and earn money!
 
More Resources



About Us    Contact Us    Privacy Policy    Terms Of Use