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:


protected void Button1_Click(object sender, EventArgs e)


string host = "localhost";

int port = 6900;

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



TcpListener tcpList = new TcpListener(addr, port);



catch (SocketException sx)


// Catch exception here if port is blocked




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)


Dim tcpList As New TcpListener(addr, port)


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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: