Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TraceRoute and Ping in C#

People also ask

What is traceroute and ping?

Ping is a simple command that can test the reachability of a device on the network. Traceroute is a command you use to 'trace' the route that a packet takes when traveling to its destination. It's useful for tracing network problems, discovering where connections fail, and tracking down latency problems.

Does traceroute use ping?

On a Windows system, traceroute uses ICMP. As with ping , traceroute can be blocked by not responding to the protocol/port being used. Traceroute displays the ICMP message's source address as the name of the hop and moves on to the next hop.

What is C ping?

-c. Specifies the number of packets. This option is useful when you get an IP trace log. You can capture a minimum of ping packets.


Given that I had to write a TraceRoute class today I figured I might as well share the source code.

using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;

namespace Answer
{  
  public class TraceRoute
  {
    private const string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    public static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress)
    {
      return GetTraceRoute(hostNameOrAddress, 1);
    }
    private static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress, int ttl)
    {
      Ping pinger = new Ping();
      PingOptions pingerOptions = new PingOptions(ttl, true);
      int timeout = 10000;
      byte[] buffer = Encoding.ASCII.GetBytes(Data);
      PingReply reply = default(PingReply);

      reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);

      List<IPAddress> result = new List<IPAddress>();
      if (reply.Status == IPStatus.Success)
      {
        result.Add(reply.Address);
      }
      else if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut)
      {
        //add the currently returned address if an address was found with this TTL
        if (reply.Status == IPStatus.TtlExpired) result.Add(reply.Address);
        //recurse to get the next address...
        IEnumerable<IPAddress> tempResult = default(IEnumerable<IPAddress>);
        tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1);
        result.AddRange(tempResult);
      }
      else
      {
        //failure 
      }

      return result;
    }
  }
}

And a VB version for anyone that wants/needs it

Public Class TraceRoute
    Private Const Data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

    Public Shared Function GetTraceRoute(ByVal hostNameOrAddress As String) As IEnumerable(Of IPAddress)
        Return GetTraceRoute(hostNameOrAddress, 1)
    End Function
    Private Shared Function GetTraceRoute(ByVal hostNameOrAddress As String, ByVal ttl As Integer) As IEnumerable(Of IPAddress)
        Dim pinger As Ping = New Ping
        Dim pingerOptions As PingOptions = New PingOptions(ttl, True)
        Dim timeout As Integer = 10000
        Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data)
        Dim reply As PingReply

        reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions)

        Dim result As List(Of IPAddress) = New List(Of IPAddress)
        If reply.Status = IPStatus.Success Then
            result.Add(reply.Address)
        ElseIf reply.Status = IPStatus.TtlExpired Then
            'add the currently returned address
            result.Add(reply.Address)
            'recurse to get the next address...
            Dim tempResult As IEnumerable(Of IPAddress)
            tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1)
            result.AddRange(tempResult)
        Else
            'failure 
        End If

        Return result
    End Function
End Class

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

public static IEnumerable<IPAddress> 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.

Although the Base Class Library includes Ping, the BCL does not include any tracert functionality.

However, a quick search reveals two open-source attempts, the first in C# the second in C++:

  • http://www.codeproject.com/KB/IP/tracert.aspx
  • http://www.codeguru.com/Cpp/I-N/network/basicnetworkoperations/article.php/c5457/

For the ping part, take a look at the Ping class on MSDN.


Ping: We can use the Ping class built into the .NET Framework.

Instantiate a Ping and subscribe to the PingCompleted event:

Ping pingSender = new Ping();
pingSender.PingCompleted += PingCompletedCallback;

Add code to configure and action the ping, e.g.:

string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
string who = "www.google.com";
AutoResetEvent waiter = new AutoResetEvent(false);
int timeout = 12000;

PingOptions options = new PingOptions(64, true);

pingSender.SendAsync(who, timeout, buffer, options, waiter);

Add a PingCompletedEventHandler:

public static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
    ... Do stuff here
}

Code-dump of a full working example, based on MSDN's example:

public static void Main(string[] args)
{
    string who = "www.google.com";
    AutoResetEvent waiter = new AutoResetEvent(false);

    Ping pingSender = new Ping();

    // When the PingCompleted event is raised,
    // the PingCompletedCallback method is called.
    pingSender.PingCompleted += PingCompletedCallback;

    // Create a buffer of 32 bytes of data to be transmitted.
    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    byte[] buffer = Encoding.ASCII.GetBytes(data);

    // Wait 12 seconds for a reply.
    int timeout = 12000;

    // Set options for transmission:
    // The data can go through 64 gateways or routers
    // before it is destroyed, and the data packet
    // cannot be fragmented.
    PingOptions options = new PingOptions(64, true);

    Console.WriteLine("Time to live: {0}", options.Ttl);
    Console.WriteLine("Don't fragment: {0}", options.DontFragment);

    // Send the ping asynchronously.
    // Use the waiter as the user token.
    // When the callback completes, it can wake up this thread.
    pingSender.SendAsync(who, timeout, buffer, options, waiter);

    // Prevent this example application from ending.
    // A real application should do something useful
    // when possible.
    waiter.WaitOne();
    Console.WriteLine("Ping example completed.");
}

public static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
    // If the operation was canceled, display a message to the user.
    if (e.Cancelled)
    {
        Console.WriteLine("Ping canceled.");

        // Let the main thread resume. 
        // UserToken is the AutoResetEvent object that the main thread 
        // is waiting for.
        ((AutoResetEvent)e.UserState).Set();
    }

    // If an error occurred, display the exception to the user.
    if (e.Error != null)
    {
        Console.WriteLine("Ping failed:");
        Console.WriteLine(e.Error.ToString());

        // Let the main thread resume. 
        ((AutoResetEvent)e.UserState).Set();
    }

    Console.WriteLine($"Roundtrip Time: {e.Reply.RoundtripTime}");

    // Let the main thread resume.
    ((AutoResetEvent)e.UserState).Set();
}

This is the most efficient way I could think of. Please vote it up if you like it so others can benefit.

    using System;
    using System.Collections.Generic;
    using System.Net.NetworkInformation;

    namespace NetRouteAnalysis
    {
        class Program
        {
            static void Main(string[] args)
            {
                var route = TraceRoute.GetTraceRoute("8.8.8.8")

                foreach (var step in route)
                {
                    Console.WriteLine($"{step.Address,-20} {step.Status,-20} \t{step.RoundtripTime} ms");
                }
            }
        }

        public static class TraceRoute
        {
            public static IEnumerable<PingReply> GetTraceRoute(string hostnameOrIp)
            {
                // Initial variables
                var limit = 1000;
                var buffer = new byte[32];
                var pingOpts = new PingOptions(1, true);
                var ping = new Ping();               

                // Result holder.
                PingReply result = null;

                do
                {
                    result = ping.Send(hostnameOrIp, 4000, buffer, pingOpts);
                    pingOpts = new PingOptions(pingOpts.Ttl + 1, pingOpts.DontFragment);

                    if (result.Status != IPStatus.TimedOut)
                    {
                        yield return result;
                    }
                }
                while (result.Status != IPStatus.Success && pingOpts.Ttl < limit);
            }
        }       
    }