Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking if port is blocked

Status
Not open for further replies.

robUK2

Programmer
Mar 10, 2008
57
TH
Hello,

VS 2008 SP1

I have been testing with that code.

However, I find that sometime it works and sometimes it doesn't. Very strange. I am wondering if there is a better way to do this.

I have checked this with netstat -aon (cmd). So I can check to see if the port is open.

I am not sure if it depends on the application using the port or not.

Any suggestions,

Thanks,


Code:
private bool IsPortAvailable() 
        { 
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); 
            bool available = false;  
            sock.Connect(VaxSIPUserAgentOCX.GetMyIP(), 5060); 
 
            if (sock.Connected) 
            { 
                //Port is available 
                available = true; 
            } 
            else 
            { 
                //Port is blocked 
                available = false; 
            } 
            return available; 
        }
 
Hi,

Have you tried using TCPClient? Code will raise an exception if it can't connect

Code:
TcpClient TcpScan = new TcpClient();
try
{
  TcpScan.Connect(IP, CurrPort); 
  MessageBox.Show("Port " + CurrPort + " open"); 

} 
catch 
{ 
  MessageBox.Show("Port " + CurrPort + " closed"); 
}

Ryan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top