Ping a machine using C#

Ping is used to test the reachability of a host on an Internet Protocol(IP) network and to measure the round-trip time for messages sent from the originating host to a destination computer. Microsoft .Net provides Ping class which is present in System.Net.NetworkInformation Namespace to ping a machine.

Ping class provide Send() method with Hostname/Address and timeout as a parameter. Send() method returns PingReply object which provides information about the ICMP(Internet Control Message Protocol) echo message if message was received or it will provides the reason for the failure if no message was received. If ICMP echo message is not received within time specified in the timeout parameter than Status property will be set to TimedOut. If an attempt to send an ICMP echo request and receive the corresponding ICMP echo reply Successfully than Status property is set as Success.

Using the properties of PingReply Class, We can find Address, Roundtrip Time, Status etc.

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Net.NetworkInformation;   
  6.   
  7. namespace PingApplication   
  8. {   
  9.    class Program   
  10.    {      
  11.       static void Main(string[] args)   
  12.       {   
  13.          string hostname = "www.bing.com";   
  14.          int timeout = 10000;   
  15.          Ping ping = new Ping();   
  16.          try   
  17.          {   
  18.             PingReply pingreply = ping.Send(hostname, timeout);   
  19.             if (pingreply.Status == IPStatus.Success)   
  20.             {   
  21.                Console.WriteLine("Address: {0}", pingreply.Address);   
  22.                Console.WriteLine("status: {0}",pingreply.Status);   
  23.                Console.WriteLine("Round trip time: {0}", pingreply.RoundtripTime);   
  24.             }   
  25.          }   
  26.          catch (PingException ex)   
  27.          {   
  28.             Console.WriteLine(ex);   
  29.          }   
  30.          Console.ReadKey();   
  31.       }   
  32.    }   
  33. }   
Preview



Hope you like it. Thanks

 

Ebook Download
View all
Learn
View all