Friday, December 28, 2007

Ping A Server In C# and .NET 2.0

The code below shows how to ping a server from .NET 2.0 (Also works in .NET 3.5)
It is a console app but you can modify the code to use in your class


using System;
using System.Net;
using System.Net.NetworkInformation;

namespace PingProc
{
class Program
{
static void Main(string[] args)
{
Ping("127.0.0.1");
//Ping("cnn.com");
}


public static int Ping(string hostname)
{
Ping ping = new Ping();

PingReply reply = ping.Send(hostname);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address);
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);
Console.WriteLine("Status: {0}", reply.Status);

Console.ReadLine();
return (0);
}
else
{
Console.WriteLine("Error");
Console.WriteLine("Status: {0}", reply.Status);
Console.ReadLine();
return (1);
}
}
}
}

No comments: