How may I ping a hostname on a network?
Asked
Active
Viewed 6.0k times
3 Answers
31
The System.Net.NetworkInformation Namespace is what you need. This link has more details
public static string PingHost(string host)
{
//string to hold our return messge
string returnMessage = string.Empty;
//IPAddress instance for holding the returned host
IPAddress address = GetIpFromHost(ref host);
//set the ping options, TTL 128
PingOptions pingOptions = new PingOptions(128, true);
//create a new ping instance
Ping ping = new Ping();
//32 byte buffer (create empty)
byte[] buffer = new byte[32];
//first make sure we actually have an internet connection
if (HasConnection())
{
//here we will ping the host 4 times (standard)
for (int i = 0; i < 4; i++)
{
try
{
//send the ping 4 times to the host and record the returned data.
//The Send() method expects 4 items:
//1) The IPAddress we are pinging
//2) The timeout value
//3) A buffer (our byte array)
//4) PingOptions
PingReply pingReply = ping.Send(address, 1000, buffer, pingOptions);
//make sure we dont have a null reply
if (!(pingReply == null))
{
switch (pingReply.Status)
{
case IPStatus.Success:
returnMessage = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl);
break;
case IPStatus.TimedOut:
returnMessage = "Connection has timed out...";
break;
default:
returnMessage = string.Format("Ping failed: {0}", pingReply.Status.ToString());
break;
}
}
else
returnMessage = "Connection failed for an unknown reason...";
}
catch (PingException ex)
{
returnMessage = string.Format("Connection Error: {0}", ex.Message);
}
catch (SocketException ex)
{
returnMessage = string.Format("Connection Error: {0}", ex.Message);
}
}
}
else
returnMessage = "No Internet connection found...";
//return the message
return returnMessage;
}

Vinay B R
- 8,089
- 2
- 30
- 45
-
Can you please include the source for the GetIpFromHost method here? (I understand that it's in the link, but the answer doesn't really work without it.) Thanks. – BrainSlugs83 May 16 '13 at 16:16
-
1Actually, upon closer inspection it looks like replacing that line with: "var address = Dns.GetHostEntry(host).AddressList.First();" is good enough -- and it would no longer swallow valuable exceptions. – BrainSlugs83 May 16 '13 at 16:21
-
1HasConnection() is not defined. – Dave Feb 14 '14 at 18:39
-
1It seems for IP v6 addresses, pingReply.Options is null – Jeroen K Sep 04 '14 at 10:43
-
Worked for me, new Uri(host).Host is Host Address and HasConnection() is System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(). BTW IMO Returning pingStatus and throwing exception is better. – Davut Gürbüz Nov 28 '14 at 13:43
-
@JeroenK yes, and its an annoying undocumented 'feature'. [referencesource](http://referencesource.microsoft.com/#System/net/System/Net/NetworkInformation/PingReply.cs,1a7446d93042c0df) – jasper Feb 12 '16 at 17:59
-
1I found that with repeated calls, I had a slow memory leak with this implementation (Visual Studio 2012, Server 2016, .NET Framework 4.6.2). Fixed it with `using Ping ping = new Ping()) { ... }` – Tony Mar 20 '18 at 20:14
-
What's more annoying than an undocumented feature is an answer that is missing definitions for a certain object. Like `HasConnection()` in this particular answer. There may be different ways to check whether there is a connection, but none are guaranteed to be compatible with this code. In short... Did this code come out of theory or is it actually available to recreate? If not, then it breaks the site's rules a of this year, at least. – IOviSpot Aug 16 '21 at 11:03
9
I would use the Ping class.

linuxuser27
- 7,183
- 1
- 26
- 22
-
10
-
Yeah I know. I waited to make sure answers were accepted before posting though. – linuxuser27 Sep 11 '10 at 04:09
4
Try this
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace Examples.System.Net.NetworkInformation.PingTest
{
public class PingExample
{
// args[0] can be an IPaddress or host name.
public static void Main (string[] args)
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine ("Address: {0}", reply.Address.ToString ());
Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
}
}
}
}

Shrikant Soni
- 2,337
- 2
- 30
- 35
-
17Please reference your code snippet. That is just a copy from the MSDN link. – linuxuser27 Sep 11 '10 at 17:40