TraceRoute Whidbey using System.Net.NetworkInformation...

Well, it appears that the new Whidbey Ping class is ultra-effective.  I've created a basic TraceRoute application making use of the API, that mimics most of the commands I have available on my XP based tracert.  I've tried to use as many neat features of the ping class as possible.  The basic algorithm is:

  • Resolve the remote host if we need to
  • Ping the remote host using TTL options so that we get the first intermediate host
  • Ping the intermediate host to see how far away it is
  • Repeat until we've reached our destination or the maximum allowed hops

I'm not even going to pretend the code is perfect, and some issues probably snuck in.  I coded this while checking out a bunch of editing features.  Gotta love full document formatting, and unlike with VS .NET 2003, this was actually fairly easy and quite robust.  Anyway, here goes TraceRoute .NET:

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Net.NetworkInformation;

#endregion

namespace DWC.NetworkUtilities {
    class TraceRoute {
        private static string usageString = @"

Usage: TraceRoute [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name

Options:
    -d                 Do not resolve addresses to hostnames.
    -h maximum_hops    Maximum number of hops to search for target.
    -w timeout         Wait timeout milliseconds for each reply.
";
        static void Main( string[] args ) {
            if ( args.Length == 0 ) {
                Console.WriteLine( usageString );
                Environment.Exit( 1 );
            }
            string targetName = null;
            IPAddress target = IPAddress.None;
            bool resolveHostnames = true;
            int maxHops = 30;
            int timeout = 30000;
            int ttl = 1;
            Ping pinger = new Ping();
            bool finished = false;

            for ( int i = 0; i < args.Length; i++ ) {
                if ( args[i].StartsWith( "-" ) ) {
                    if ( args[i] == "-d" ) {
                        resolveHostnames = false;
                    } else if ( args[i] == "-h" && ( i + 1 ) < args.Length ) {
                        i++;
                        int.TryParse( args[i], out maxHops );
                    } else if ( args[i] == "-w" && ( i + 1 ) < args.Length ) {
                        i++;
                        int.TryParse( args[i], out timeout );
                    }
                } else {
                    try {
                        target = IPAddress.Parse( args[i] );
                    } catch {
                        try {
                            IPHostEntry hostEntry = Dns.GetHostByName( args[i] );
                            targetName = hostEntry.HostName;
                            target = hostEntry.AddressList[0];
                        } catch {
                            Console.WriteLine( usageString );
                            Environment.Exit( 2 );
                        }
                    }
                }
            }

            Console.WriteLine();
            Console.Write( "Tracing route to {0} ", ( targetName != null ) ? targetName : target.ToString() );
            if ( targetName != null ) { Console.Write( "[{0}] ", target.ToString() ); }
            Console.WriteLine( "over a maximum of {0} hops:", maxHops );
            Console.WriteLine();

            do {
                PingReply reply = pinger.Send( target, new byte[0], timeout, new PingOptions( ttl++, true ) );
                IPAddress replyAddress = reply.Address;
                if ( reply.Status == IPStatus.Success ) {
                    finished = true;
                }

                Console.Write( "{0, 3}", ttl - 1 );
                PingReply timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
                Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );
                timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
                Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );
                timing = pinger.Send( replyAddress, new byte[50], timeout, new PingOptions( 128, true ) );
                Console.Write( "{0, 5} ms", ( timing.Status == IPStatus.Success ) ? timing.RoundTripTime.ToString() : "*" );

                string hostName = null;
                if ( resolveHostnames ) {
                    try {
                        IPHostEntry hostEntry = Dns.GetHostByAddress( replyAddress );
                        if ( hostEntry.HostName != null && hostEntry.HostName != string.Empty ) {
                            hostName = hostEntry.HostName;
                        }
                    } catch { }
                }

                Console.WriteLine(
                    ( hostName != null ) ? "  {0} [{1}]" : "  {0}",
                    ( hostName != null ) ? hostName : replyAddress.ToString(),
                    replyAddress );
            } while ( !finished && ttl <= maxHops );

            Console.WriteLine();
            Console.WriteLine( "Trace complete, {0}", ( finished ) ? "destination reached" : "ttl expired reaching destination" );
        }
    }
}

 

Published Wednesday, June 09, 2004 5:38 AM by Justin Rogers
Filed under: ,

Comments

Wednesday, June 09, 2004 12:14 PM by TrackBack

# System.Net.NetworkInformation.Ping

After sorting out a problem with some ICMP "ping" code last week, it was nice to see that there is a Ping class in Whidbey, as described in Justin Rogers' post TraceRoute Whidbey using System.Net.NetworkInformation....
Monday, March 17, 2008 10:28 PM by copy dvd movies

# copy dvd movies

Assistance from RWC Computer Services Your browser doesn\'t support IFrames. a href \"http:// siteneighbors. com/ blogs/ widget/ 86\" target \"_ blank\" Visit this blog\'s neighborhood. /

Tuesday, March 18, 2008 12:05 AM by windows dvd decoders

# windows dvd decoders

Square Enix’ s“ White Engine,” now renamed the Crystal Tools, has been confirmed for work on platforms of PS3, XBox 360 and PC. Also they did announce that they will be using a dumbed down version of Crystal Tools for the Wii Platform. They also showed

Tuesday, March 18, 2008 3:20 AM by how record dvd

# how record dvd

Computer Virus- First Look: Internet Cleanup 5.

Tuesday, March 18, 2008 4:13 AM by shrink dvd

# shrink dvd

Download SugarSync onto your computer (on as many computers as you’ d like, though you only need one), set which folders you’ d like to have synced, and you’ re set. It’ s so easy to use and such a great resource. No more emailing files to myself on gmail

Wednesday, March 19, 2008 11:13 PM by dvd burning software

# dvd burning software

Zoom Player is the most Powerful, Flexible and Customizable DVD and Media Player for the Windows PC platform. Using our powerful Smart Play technology, more media formats play with less hassle, improved stability and greater performance.

Friday, March 21, 2008 2:08 AM by dvd decrypt freeware

# dvd decrypt freeware

Categories News Accessories Reviews Previews GameSoul News Video Games Console Wii Ps3 Ps2 Retro Gaming XBOX XBOX 360 Gamecube PC HandHelds PSP Nintendo DS Gameboys Online Gaming Board Games Genre RPG/

Monday, April 14, 2008 5:13 AM by where to download movies

# where to download movies

Sho‘ Nuff, Camp is abound in what is easily one of the best action movies ever made in Walter Hill’ s depiction of Inner- city gangs taking place in New York city. The plot is simple but extremely action packed as a famous and beloved gang kingpin is

Wednesday, April 30, 2008 3:03 PM by lease option

# lease option

Can you imagine the potential damage/ disaster that could come about with a code breach? Think about it. We’ re talking about libraries that allow you to tie into each and every xmlhttp request… heck, every form for that matter as well. Form. extend(

Friday, May 09, 2008 6:25 PM by Internet Business Training Program

# Internet Business Training Program

some take time others take money.

# Reformed Adult Webmaster Reveals Cutting-Edge Marketing Secrets

Detailed Monthly Archive 29: Bido Preview Site Goes Live (13) 29: Why Am I Missing Out On Great Deals? (12) 29: Search Engine Land: Is IAC Ready To Drop Ask. com Search Technology & Partner With Google? (0) 29: Rick Latona: To the Top! The Mt. Kilimanjaro

Thursday, June 05, 2008 4:01 PM by game coping software

# game coping software

More Photos/ Subscribe Via Email Subscribe To ORKUT An Epitome: Linux Rocks by Email/ Special Days An error has occurred; the feed is probably down. Try again later. / Page Content About About Orkut Fedora 8: Guide Orkut Security Orkut Tips & Tricks Pc

Tuesday, June 24, 2008 7:58 PM by List of best diet pills

# List of best diet pills

Interesting article.

Thursday, July 24, 2008 10:53 PM by Watch movies online

# Watch movies online

Most Popular Posts are describing how to Download full length movies or how to watch movie online... Both has never been easier...

# Stay at home mom resource for making extra money online.

Join us today as we discuss The Vaccine Book b y Robert W. Sears. This is the second time that contributors of Silicon Valley Moms Blog , Chicago Moms Blog, DC Metro Moms Blog and NYC Moms Blog (along with the rest our friends throughout the blogsphere

Saturday, September 20, 2008 1:28 PM by 4xtrainings.com

# 4xtrainings.com

Make Money the Easy Way have any inkling to the sport that’ s what I think of every handle emotional stress issues, there are dolls. The technology- oriented children of today are several reasons to choose a that you thoroughly read the fine is practiced

Monday, September 22, 2008 4:42 AM by investing foreign currency

# investing foreign currency

You’ re the one that has to be the translator, though. The market shouldn’ t be interpreted by some indicator. For example, if you moved to a foreign country for a year, aren’ t you going to at least try to learn the language. Sure, you can probably find

Thursday, October 02, 2008 1:37 PM by p90x

# p90x

Cindy Philips is the founder and director of Island Yoga Space. She\'s been teaching \'movement arts\' since 1986 and holds a BA in Performing Arts from Southern Oregon University, Vinyasa Yoga Teacher Certification from White Lotus Foundation and a 200

Tuesday, November 24, 2009 9:16 PM by protein weight loss

# protein weight loss

... good ideas on losing weight ...

Leave a Comment

(required) 
(required) 
(optional)
(required)