How to Use Ping in C#

Introduction

Whether it is a Web Server or any local computer, if you really want to check its availability then there is a way to do it. A common way to do this is PING.

Actually, it sends a small packet (ICMP) of data to the Web Server or network machine. If it accepts it then the connection is approved else you get a Timeout error and that tells you it can't connect with them.

setup connection

Background

We don't need extra knowledge of networking except C#.

Procedures

Step1: Add the System.Net.NetworkInformation namespace to your project.

Step 2: Now, we want a Ping object to get started.
 

Ping myPing = new Ping();

Then, we ask for a response from the pinged device or server.

For this, we need to use the Send() method and we two arguments within it.

First will be the Host Name and then the timeout time.

PingReply reply = myPing.Send("192.168.1.3", 1000);

And, it's a PingReply type, so before casting ensure that you have the correct type.

And, then use Status, Time and Address field to get the value.

Console.WriteLine("Status :  " + reply.Status + " \n Time : " + reply.RoundtripTime.ToString() + " \n Address : " + reply.Address);

The code will look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation; //Include this

namespace PingProto
{
    public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Ping myPing = new Ping();
                PingReply reply = myPing.Send("192.168.1.3", 1000);
                if (reply != null)
                {
                     Console.WriteLine("Status :  " + reply.Status + " \n Time : " + reply.RoundtripTime.ToString() + " \n Address : " + reply.Address);
                    //Console.WriteLine(reply.ToString());

                }
            }
            catch
            {
                Console.WriteLine("ERROR: You have Some TIMEOUT issue");
            }
             Console.ReadKey();
        }
    }
}

And, you will get something like this:

PING

Instead of host name, you can use any web site (http://google.com) or server address to check if they are active or not.

Conclusion

In this we try to check the nature of a network device or web server using some kind of PING. Still, if you encounter any problem then you can go for the attached solution file.

Up Next
    Ebook Download
    View all
    Learn
    View all