Skip to content

Instantly share code, notes, and snippets.

@Mailaender
Created March 10, 2013 19:33
Show Gist options
  • Save Mailaender/5130047 to your computer and use it in GitHub Desktop.
Save Mailaender/5130047 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);
packetLoss = (failedPings / pingAmount) * 100;
}
@xiaoli
Copy link

xiaoli commented Sep 15, 2017

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