Ping结果与ping.exe报告的结果不同

时间:2015-02-14 23:03:35

标签: c# windows networking ping

我正在使用此代码ping几个网站:

    public static async Task<long> PingUrl(string url)
    {
        using (var ping = new Ping())
        {
            var result = await ping.SendPingAsync(url, 1000);
            return result.RoundtripTime;
        }
    }

然后这样称呼:

    private async void RunPing()
    {
        long urlTotal, total = 0;
        int count, totalCount = 0;
        txtResult.Text = string.Empty;            

        for (int i = 0; i < urls.Length; i++)
        {
            txtResult.Text += string.Format("{0}:{1}", names[i], Environment.NewLine);
            urlTotal = count = 0;
            for (int j = 0; j < 4; j++)
            {
                var duration = await Utilities.PingUrl(urls[j]);
                if (duration > 0)
                    ++count;

                urlTotal += duration;
                txtResult.Text += string.Format("{0}{1}", duration > 0 ? duration.ToString() + "ms" : "Not reachable", Environment.NewLine);
            }

            if (count == 0)
            {
                txtResult.Text += (string.Format("Not reachable{1}----------------------{1}", urlTotal / count, Environment.NewLine));
            }
            else
            {
                txtResult.Text += (string.Format("Average: {0}{1}----------------------{1}", urlTotal / count, Environment.NewLine));
            }

            total += urlTotal;
            totalCount += count;
        }

        txtResult.Text += (string.Format("{1}Total average: {0}{1}{1}", total / totalCount, Environment.NewLine));
    }

结果如下:

4.2.2.4 DNS:
Not reachable
147ms
Not reachable
Not reachable
Average: 147
----------------------
8.8.8.8 DNS:
260ms
148ms
Not reachable
Not reachable
Average: 204

...

但是从命令行使用ping.exe会给我:

> ping 8.8.8.8

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=147ms TTL=50
Reply from 8.8.8.8: bytes=32 time=158ms TTL=50
Reply from 8.8.8.8: bytes=32 time=147ms TTL=50
Reply from 8.8.8.8: bytes=32 time=147ms TTL=50

这更加一致。有什么不同吗?我希望能够得到相同的结果。

PS:更改超时并使用方法的sync版本(ping.Send())给出了确切的结果。

0 个答案:

没有答案