Using Ping in C#

Making a ping inside of my C# application

Give a look the NetworkInformation.Ping class.

An example:

Usage:

PingTimeAverage("stackoverflow.com", 4);

Implementation:

public static double PingTimeAverage(string host, int echoNum)
{
long totalTime = 0;
int timeout = 120;
Ping pingSender = new Ping ();

for (int i = 0; i < echoNum; i++)
{
PingReply reply = pingSender.Send (host, timeout);
if (reply.Status == IPStatus.Success)
{
totalTime += reply.RoundtripTime;
}
}
return totalTime / echoNum;
}

How to run PING command and get ping host summary in C#?

Use this example:

var startInfo = new ProcessStartInfo( @"cmd.exe", "/c ping -n 8 google.com" )
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};

var pingProc = new Process { StartInfo = startInfo };
pingProc.Start();

pingProc.WaitForExit();

var result = pingProc.StandardOutput.ReadToEnd();

Console.WriteLine( result );
Console.ReadKey();

If you need know about ping result here example:

...
pingProc.WaitForExit();

var reader = pingProc.StandardOutput;
var regex = new Regex( @".+?\s+=\s+(\d+)(,|$)" );

var sent = 0;
var recieved = 0;
var lost = 0;

string result;
while ( ( result = reader.ReadLine() ) != null )
{
if ( String.IsNullOrEmpty( result ) )
continue;

var match = regex.Matches( result );
if ( match.Count != 3 )
continue;

sent = Int32.Parse( match[0].Groups[1].Value );
recieved = Int32.Parse( match[1].Groups[1].Value );
lost = Int32.Parse( match[2].Groups[1].Value );
}

var success = sent > 0 && sent == recieved && lost == 0;

Is it possible pinging with C# like in the CMD?

If the domain have IPv4 and IPv6 addresses, you'll get both. Filter by AddressFamily to InterNetwork only (IPv4) instead of InterNetworkV6 (IPv6)

var ipV4Address = Dns.GetHostAddresses(domain)
.First(a => a.AddressFamily == AddressFamily.InterNetwork);

Using ping in a foreach loop in C#

I would restructure your solution a bit. The ping code should run its own thread. Remove the timer, and simply block on Console.ReadLine(). If the results are not expected, repeat until you get either stop or exit.

The reason is the ping work and the console processing are on the same thread. These will block.

Try this:

class Program
{
static void Main(string[] args)
{
Console.WriteLine("pinging....until stop command");
Thread pinger = new Thread(DoPinging);
pinger.Start();

while (true)
{
string command = Console.ReadLine();

if (command.ToLower() == "stop")
break;

else if (command.ToLower() == "exit")
break;

Console.WriteLine("Ignoring-> " + command);
}

pinger.Abort();
}

static void DoPinging()
{
// here goes the pinging code
}
}

In your example code, it looks like you want to read input for ping from Console as well, after the line read, if the value doesn't equal the stop commands (stop, exit), put the value into a queue and let the ping code read from the queue.

You mention reading a CSV file for the addresses to ping (but your example code doesn't reference a file). You can take this as a command line argument (string[] passed in main) and do the work for processing the file in the DoPinging method.

If you want me to add more detail to that, please comment below and I will work on that.

Thnx
Matt

C# Continuous Ping

Put this line:

bool boCheckbox = cbContinuousPing.Checked;

inside your while loop.

How to read from servers from .txt file and ping them with C# Application?

You can use File.ReadAllLines to read all the text inside a file and loop through the lines.

So, this should solve your problem:

using System;
using System.IO;
using System.Threading;

namespace SO.DtProblem
{
class Program
{
static void Main(string[] args)
{
var servers = File.ReadAllLines(@"C:\temp\servers.txt");

foreach (var line in servers)
{
string currentServer = line;
//Your ping code per currentServer should be here
//Or do somthing else as you wish

Console.WriteLine(line);
}

}
}
}

Actual/Hard Timeout with Ping in C#

Put the ping call inside a Task and Wait() up to your chosen timeout, after that has completed or timed out, we check to see if reply was set.

I've implemented this into your code below

//.NETCore.App\3.1.4
// Microsoft Visual Studio Community 2019 - Version 16.5.5
// Microsoft Windows [Version 10.0.18362.836]

using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

class Program
{
public static void Main(string[] args)
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();

string who = String.Empty;

//who = "firewall0"; //Hostname of my local firewall
//who = "www.yahoo.com";
who = "not-a-valid-host";
//who = "10.1.1.151"; //My interface
//who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
//who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
//who = "127.0.0.1";

string data = "Using Ping in C#Using Ping in C#Using Ping in C#Using Ping in C#";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1;
int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
Ping pingSender = new Ping();
PingOptions options = new PingOptions(numMaxHops, true);

if (false) //Use false to toggle off this section of code while testing
{
AutoResetEvent waiter = new AutoResetEvent(false);
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
Console.WriteLine("Time to live set to: {0}", options.Ttl);
Console.WriteLine("");
pingSender.SendAsync(who, timeout, buffer, options, waiter);
waiter.WaitOne();
Console.WriteLine("Ping example completed.");
}

if (true) //Use false to toggle off this section of code while testing
{
try
{
PingReply reply = null;

var t = Task.Run(() =>
{
reply = pingSender.Send(who, timeout, buffer, options);
Console.WriteLine("Ping example completed.");
});

t.Wait(TimeSpan.FromMilliseconds(100));

if (reply == null)
{
Console.WriteLine("timed out");
}
else if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
if (reply.Address.ToString() != "::1")
{
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);
}
}
else
{
Console.WriteLine(reply.Status);
}
}
catch (Exception ex)
{
Regex noHostMatch = new Regex("No such host is known");
if (noHostMatch.IsMatch(ex.InnerException.ToString()))
//if (false)
{
Console.WriteLine("No such host is known.");
}
else
{
throw;
}
}
}

watch.Stop();
Console.WriteLine("");
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
Console.WriteLine("Press the Enter key");
Console.ReadLine();
}//End Main()

private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.

if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");

// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set();
}

// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
//Console.WriteLine(e.Error.ToString());

// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply reply = e.Reply;
DisplayReply(reply);

// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}

}//End PingCompletedCallback()

public static void DisplayReply(PingReply reply)
{
if (reply == null)
return;

Console.WriteLine("Ping Status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Address: {0}", reply.Address.ToString());
Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

if (reply.Address.ToString() != "::1")
{
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);
}
}
}//End DisplayReply()
}

TraceRoute and Ping in C#

Although the Base Class Library includes Ping, the BCL does not include any tracert functionality.

However, a quick search reveals two open-source attempts, the first in C# the second in C++:

  • http://www.codeproject.com/KB/IP/tracert.aspx
  • http://www.codeguru.com/Cpp/I-N/network/basicnetworkoperations/article.php/c5457/


Related Topics



Leave a reply



Submit