How to check if a TCP port is blocked using C# or VB.NET

In order to check if a TCP port is blocked, use the System.Net and System.Net.Sockets classes as shown below:

C#


protected void Button1_Click(object sender, EventArgs e)


{


string host = "localhost";


int port = 6900;


IPAddress addr = (IPAddress)Dns.GetHostAddresses(host)[0];


try


{


TcpListener tcpList = new TcpListener(addr, port);


tcpList.Start();


}


catch (SocketException sx)


{


// Catch exception here if port is blocked


}


}





VB.NET


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)


Dim host As String = "localhost"


Dim port As Integer = 6900


Dim addr As IPAddress = CType(Dns.GetHostAddresses(host)(0), IPAddress)


Try


Dim tcpList As New TcpListener(addr, port)


tcpList.Start()


Catch sx As SocketException


' Catch exception here if port is blocked


End Try


End Sub




Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: