C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Check if a port is open or closed?


Posted Date: 02 May 2007    Resource Type: Code Snippets    Category: Network

Posted By: Balamurali Balaji       Member Level: Diamond
Rating:     Points: 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

Author: Abhishek Arya    22 Sep 2008Member Level: Diamond   Points : 0
Good one it works for me


Feedbacks      
Popular Tags   What are tags ?   Search 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 Discussion Resource Index
Post New Resource
Category: Network


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

SPOC

Contact Us    Privacy Policy    Terms Of Use