TraceRoute and Ping in C#

后端 未结 6 743
我在风中等你
我在风中等你 2020-11-27 14:25

Does anyone have C# code handy for doing a ping and traceroute to a target computer? I am looking for a pure code solution, not what I\'m doing now, which is invoking the p

6条回答
  •  天命终不由人
    2020-11-27 15:03

    What follows is a significantly better C# implementation of tracert than exists in other answers thus far.

    public static IEnumerable GetTraceRoute(string hostname)
    {
        // following are similar to the defaults in the "traceroute" unix command.
        const int timeout = 10000;
        const int maxTTL = 30;
        const int bufferSize = 32;
    
        byte[] buffer = new byte[bufferSize];
        new Random().NextBytes(buffer);
    
        using (var pinger = new Ping())
        {
            for (int ttl = 1; ttl <= maxTTL; ttl++)
            {
                PingOptions options = new PingOptions(ttl, true);
                PingReply reply = pinger.Send(hostname, timeout, buffer, options);
    
                // we've found a route at this ttl
                if (reply.Status == IPStatus.Success || reply.Status == IPStatus.TtlExpired)
                    yield return reply.Address;
    
                // if we reach a status other than expired or timed out, we're done searching or there has been an error
                if (reply.Status != IPStatus.TtlExpired && reply.Status != IPStatus.TimedOut)
                    break;
            }
        }
    }
    

    Pitfalls fixed here that are present in other answers include:

    • It's lazy. Ex: it properly uses enumerable / an iterator so don't have to compute the entire tree, you can stop at any point by breaking out of your own consuming loop.
    • maxTTL implemented so the function doesnt spin on forever.
    • bufferSize option which is consistent with other tracert implementations.
    • It's super concise and clean. It's contained in a single method and is considerably shorter than other options here.

提交回复
热议问题