Skip to content

Instantly share code, notes, and snippets.

@xiaoli
Forked from Mailaender/Ping.cs
Last active September 15, 2017 02:58
Show Gist options
  • Save xiaoli/6939dfe9673608a053685f17e9c7c7d3 to your computer and use it in GitHub Desktop.
Save xiaoli/6939dfe9673608a053685f17e9c7c7d3 to your computer and use it in GitHub Desktop.
Ping a host and calculate packet loss.
void GetNetworkStats(string host, int pingAmount, int timeout, out int averagePing, out int packetLoss)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions(); // default is: don't fragment and 128 Time-to-Live
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data); // 32 bytes of data
var failedPings = 0;
var latencySum = 0;
for (int i = 0; i < pingAmount; i++)
{
PingReply reply = pingSender.Send(host, timeout, buffer, options);
if (reply != null)
{
if (reply.Status != IPStatus.Success)
failedPings += 1;
else
latencySum += (int)reply.RoundtripTime;
}
}
averagePing = (latencySum / (pingAmount - failedPings));
packetLoss = Convert.ToInt32((Convert.ToDouble(failedPings) / Convert.ToDouble(pingAmount)) * 100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment