How to implement PsPing TCP ping in C#

前端 未结 3 1246
臣服心动
臣服心动 2020-12-25 08:09

I am trying to implement Mark Russinovich\'s SysInternals PsPing tool in C# to measure latencies using TCP ping.

I am not sure how it makes the ping call (apparently

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 08:49

    I have tried several approaches, first thinking I had to use raw sockets or at least use native calls, but a simple TCP connect and close seems to create exactly the same results as the psping utility:

    var times = new List();
    for (int i = 0; i < 4; i++)
    {
        var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.Blocking = true;
    
        var stopwatch = new Stopwatch();
    
        // Measure the Connect call only
        stopwatch.Start();
        sock.Connect(endPoint);
        stopwatch.Stop();
    
        double t = stopwatch.Elapsed.TotalMilliseconds;
        Console.WriteLine("{0:0.00}ms", t);
        times.Add(t);
    
        sock.Close();
    
        Thread.Sleep(1000);
    }
    Console.WriteLine("{0:0.00} {1:0.00} {2:0.00}", times.Min(), times.Max(), times.Average());
    

    Inspecting the traffic using Wireshark, I can confirm both psping and the snippet above are creating exactly the same sequence of packets.

    -> [SYN]
    <- [SYN,ACK]
    -> [ACK]
    -> [FIN,ACK]
    <- [FIN,ACK]
    -> [ACK]
    

    Output from psping with no warm-up and using TCP ping:

    C:\>psping -w 0 stackoverflow.com:80
    
    PsPing v2.01 - PsPing - ping, latency, bandwidth measurement utility
    Copyright (C) 2012-2014 Mark Russinovich
    Sysinternals - www.sysinternals.com
    
    TCP connect to 198.252.206.16:80:
    4 iterations (warmup 0) connecting test:
    Connecting to 198.252.206.16:80: 92.30ms
    Connecting to 198.252.206.16:80: 83.16ms
    Connecting to 198.252.206.16:80: 83.29ms
    Connecting to 198.252.206.16:80: 82.98ms
    
    TCP connect statistics for 198.252.206.16:80:
      Sent = 4, Received = 4, Lost = 0 (0% loss),
      Minimum = 82.98ms, Maximum = 92.30ms, Average = 85.43ms
    

    Output from the program above:

    C:\>TcpPing.exe stackoverflow.com 80
    88.60ms
    83.65ms
    84.05ms
    84.05ms
    83.65 88.60 85.09
    

    As for measurements, I must say, sometimes there are quite a few different results at different runs, but overall they seemed pretty close: kind of proves measuring the Connect() call is good enough. I'm thinking, taking a median of a few hundred results might prove it with a bit more confidence.

提交回复
热议问题