Created
March 10, 2013 19:33
-
-
Save Mailaender/5130047 to your computer and use it in GitHub Desktop.
Ping a host and calculate packet loss.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
averagePing = (latencySum / (pingAmount - failedPings));
packetLoss = Convert.ToInt32((Convert.ToDouble(failedPings) / Convert.ToDouble(pingAmount)) * 100);