Test TCP/IP Connectivity Through aspx Page






4.67/5 (9 votes)
Test TCP/IP connectivity through aspx page

Introduction
Recently, I came across the requirement where I needed to test TCP/IP port connectivity from website hosted on IIS server to another third party server. So I created this small utility which tests the TCP/IP port connectivity using .aspx page. The good thing about this code is that it’s very portable as all the code is written in aspx page (inline code) with no code behind file which does not require any code build.
Using the Utility
Below is a brief description of how to use this utility.
Get URL IP
To get the IP of the URL you need paste the URL inside text box and click on GetIP
button
as shown in the below screenshot.
//Code for GetUrlIP method
void GetUrlIP(string serverUrl)
{
try
{
Uri uri = new Uri(serverUrl);
IPHostEntry hostName = Dns.GetHostByName(uri.Host);
string ip = hostName.AddressList[0].ToString();
divMsg.InnerHtml = "IP of " + uri.Host + ": " + ip;
}
catch (Exception ex)
{
divMsg.InnerHtml += ex.Message;
}
}
PingServer
To get the ping status of an IP, you need to put IP inside the textbox and click on Ping button as shown in the below screenshot:
//Code for PingServer method
void PingServer(string ipAddress)
{
ipAddress = ipAddress.Trim();
Ping p = new Ping();
try
{
IPAddress.Parse(ipAddress);
PingReply reply = p.Send(ipAddress, 3000);
divMsg.InnerHtml += "Pinging " + ipAddress + " with 32 bytes of data :<br>";
if (reply.Status == IPStatus.Success)
{
divMsg.InnerHtml += "Reply from " + reply.Address.ToString() +
": bytes=" + reply.Buffer.Length.ToString() + "bytes time=" +
reply.RoundtripTime.ToString() + "ms TTL=" + reply.Options.Ttl.ToString();
}
else if (reply.Status == IPStatus.TimedOut)
{
divMsg.InnerHtml += "Request time out.";
}
}
catch (Exception ex)
{
divMsg.InnerHtml += ex.Message;
}
}
ConnectToServerPort
To test TCP/IP connectivity, you need put the IP address and port number in text box and click on Test connectivity button as shown in the below screenshot:
void ConnectToServerPort(string ipAddress, int port)
{
try
{
ipAddress = ipAddress.Trim();
IPAddress IP = IPAddress.Parse(ipAddress);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
divMsg.InnerHtml += "Connecting to " + ipAddress +
" on port " + port.ToString() + "<br>";
s.Connect(IP, port);
if (s.Connected)
{
divMsg.InnerHtml += "Connected Successfully";
s.Disconnect(false);
}
else
{
divMsg.InnerHtml += "Connection Failed";
}
}
catch (Exception ex)
{
divMsg.InnerHtml += "Connection Failed" + "<br>";
divMsg.InnerHtml += ex.Message;
}
}
Deploying Code To IIS
For using this utility with your existing ASP.NET web site, you simply need to copy TestTcpIpConnectivity.aspx into your web site root folder. Afterwards, you can access it by using http://yourwebsite/TestTcpIpConnectivity.aspx.