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


No comments:

Post a Comment