简体   繁体   中英

In C# verify the ping utility

From C# console application i had open the command prompt and checked the ping utility.

string aptracommand;
aptracommand = "/C ping 10.38.2.73";
Process.Start(@"cmd",aptracommand);

Now , i need to apply a conditional statement if ping request time out then it should say "Not able to connect" and if its able to ping then need to show "Server is up"

You can use Ping class for this purpose. As stated below:

using System.Net.NetworkInformation;

var ping = new Ping();
var reply = ping.Send("10.38.2.73", 60 * 1000); // 1 minute time out (in ms)
if (reply.Status == IPStatus.Success)
{
   Console.WriteLine("Server is up");
}
else
{
   Console.WriteLine("Server is down");
}

You can reduce the time out value to quickly check if server is up or down.

use this instead

Ping pingSender = new Ping ();
byte[] data = Encoding.ASCII.GetBytes ("test");
int timeout = 100;
PingReply reply = pingSender.Send("127.0.0.1", timeout, data);
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);
}

I think you will need to capture the output, check for the existence of time out string and then take the decision based on that.

Capturing the Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM