CSharp .Net Tutorial: Pinging

James Cloud
Failing to check if a connection can be established before attempting to connect may result in unwarranted errors and problematic situations. A simple and effective way to test a connection before actually trying to connect is to ping the host or IP Address you want to connect to. If you receive a response that mean a connection is possible. If the ping routine times out than the connection will fail as you can not make contact with the host.

This tutorial will guide you through the process of pinging in Visual CSharp .Net.

Pinging an I.P. Address

Before creating the pinging function make sure you include a reference to System Net Network Information at the beginning of your class, like so:

using System.Net.NetworkInformation;

Now that you have the proper dependencies you can create a string function called PingHost with a String parameter called IPADRS. Create the String function using the source code found below:

public string PingHost(String IPADRS)
{
String Ret;

Ret = "";

using (Ping myPing = new Ping())
{

try
{

PingReply myReply = myPing.Send(IPADRS, 100);

if (myReply.Status == IPStatus.Success)
{
Ret = "Successfully Pinged IP Address: " + myReply.Address + " Time: " + myReply.RoundtripTime;
return Ret;
}
else
{
Ret = "Problem Pinging IP Address: " + myReply.Status.ToString();
return Ret;
}
}
catch (Exception ex)
{
Ret = "An Error was Encountered: " + ex.InnerException.Message;
return Ret;
}
}

return Ret;
}

This function will take the IP Address string parameter, ping it, and return the result of the pinging process making the PingHost String equal to the return value.

Conclusion

You have included the proper dependencies and create a pinging function, now all you have to do is call the function and supply the desired IP Address as a String parameter. Here is an example:

MessageBox.Show(PingHost("192.168.1.1"));

This code will attempt to ping the IP Address, 192.168.1.1, and a Message Box will show the results.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.