Wednesday, February 13, 2008

How to ping a server programatically in .net using C#

Normally, in Windows operating system we can ping a machine using Ping command in the command window. What we need to do is just provide the IP of the target machine we want to ping. Ping command returns the response which tells us that the other machine is active on the network and available. This same kind of functionality need to be achieved via programming. In this article I'll show you the code snippet which can help you ping a system in C# or Visual Basic.Net.

Microsoft.Net framework 2.0 provides Ping class under System.Net.NetworkInformation namespace which can be used to ping an IP. Following is the snippet which let you do this:

Ping objPing = new Ping();
PingReply objPingReply = objPing.Send("IP of the Machine");

if (objPingReply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}

1 comment:

Unknown said...

I trid this code, getting error
System.Net.NetworkInformation.PingException: An exception occurred during a Ping request. ---> System.Net.Sockets.SocketException: No such host is known at System.Net.Dns.GetAddrInfo(String name) at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6) at System.Net.Dns.GetHostAddresses(String hostNameOrAddress) at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress, Int32 timeout, Byte[] buffer, PingOptions options) --- End of inner exception stack trace --- at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress, Int32 timeout, Byte[] buffer, PingOptions options) at System.Net.NetworkInformation.Ping.Send(String hostNameOrAddress) at System_details.btn_ping_Click(Object sender, EventArgs e) in c:\InetPub\WWWROOT\test\system_details\system_details.aspx.cs:line 99