Click here to Skip to main content
6,295,667 members and growing! (9,867 online)
Email Password   helpLost your password?
General Reading » Hardware & System » System     Intermediate License: The GNU General Public License (GPL)

Monitoring network speed

By Echevil

Detecting upload and download speed of a network adapter using performance counters.
C#.NET 1.1, WinXP, Visual Studio, Dev
Posted:29 Feb 2004
Views:125,954
Bookmarked:97 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
28 votes for this article.
Popularity: 5.86 Rating: 4.05 out of 5
2 votes, 7.1%
1
1 vote, 3.6%
2
3 votes, 10.7%
3
3 votes, 10.7%
4
19 votes, 67.9%
5

Sample Image

Introduction

The .NET Class Library provides a set of performance counters that you can use to track the performance both of the system and of an application. This program makes use of counters in the Networking category to obtain information about data sent and received over the network, and calculates network speed.

Using the code

This library includes only two classes, NetworkMonitor and NetworkAdapter. The former one provides general methods to enumerate network adapters installed on a computer, start or stop watching specified adapter, and a timer to read performance counter samples every second, and the latter represents a specific network adapter, providing properties presenting current speed.

The following code is a simple example of using these two classes:

    NetworkMonitor monitor    =    new NetworkMonitor();
    NetworkAdapter[] adapters    =    monitor.Adapters;

    // If the length of adapters is zero, then no instance

    // exists in the networking category of performance console.

    if (adapters.Length == 0)
    {
        Console.WriteLine("No network adapters found on this computer.");
        return;
    }

    // Start a timer to obtain new performance counter sample every second.

    monitor.StartMonitoring();

    for( int i = 0; i < 10; i ++)
    {
        foreach(NetworkAdapter adapter in adapters)
        {
            // The Name property denotes the name of this adapter.

            Console.WriteLine(adapter.Name);
            // The DownloadSpeedKbps and UploadSpeedKbps are

            // double values. You can also use properties DownloadSpeed

            // and UploadSpeed, which are long values but

            // are measured in bytes per second.

            Console.WriteLine(String.Format("dl: {0:n} " + 
               "kbps\t\tul: {1:n} kbps? adapter.DownloadSpeedKbps, 
               adapter.UploadSpeedKbps));
        }
        System.Threading.Thread.Sleep(1000); // Sleeps for one second.
    }

    // Stop the timer. Properties of adapter become invalid.
    monitor.StopMonitoring ();

Points of Interest

To enumerate the network adapters on a computer, I only utilize the existing interface names in the networking category of performance console. Here is the EnumerateNetworkAdapters() method.

    /// <summary>

    /// Enumerates network adapters installed on the computer.

    /// </summary>

    private void EnumerateNetworkAdapters()
    {
        PerformanceCounterCategory category    = 
          new PerformanceCounterCategory("Network Interface");

        foreach (string name in category.GetInstanceNames())
        {
            // This one exists on every computer.

            if (name == "MS TCP Loopback interface")
                continue;
            // Create an instance of NetworkAdapter class,

            // and create performance counters for it.

            NetworkAdapter adapter = new NetworkAdapter(name);
            adapter.dlCounter = new PerformanceCounter("Network Interface", 
                                                "Bytes Received/sec", name);
            adapter.ulCounter = new PerformanceCounter("Network Interface", 
                                                    "Bytes Sent/sec", name);
            this.adapters.Add(adapter);    // Add it to ArrayList adapter

        }
    }

A tricky problem with this approach is that an instance called �MS TCP Loopback interface� exists on every computer, of which both the download speed and the upload speed are always zero. So I explicitly check and exclude it in the program, which is certainly not a good manner but workable.

Before all of this, I tried to accomplish this by making a WMI query, which looked more decent, and my first version went like this:

    /// 

    /// Enumerates network adapters installed on the computer.

    /// 

    private void EnumerateNetworkAdapters()
    {
        // Information about network adapters can be found

        // by querying the WMI class Win32_NetworkAdapter,

        // NetConnectionStatus = 2 filters the ones that are not connected.

        // WMI related classes are located in assembly System.Management.dll

        ManagementObjectSearcher searcher = new 
            ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter" + 
                                            " WHERE NetConnectionStatus=2");

        ManagementObjectCollection adapterObjects = searcher.Get();

        foreach (ManagementObject adapterObject in adapterObjects)
        {
            string name    =    adapterObject["Name"];

            // Create an instance of NetworkAdapter class,

            // and create performance counters for it.

            NetworkAdapter adapter = new NetworkAdapter(name);
            adapter.dlCounter = new PerformanceCounter("Network Interface", 
                                                "Bytes Received/sec", name);
            adapter.ulCounter = new PerformanceCounter("Network Interface", 
                                                    "Bytes Sent/sec", name);
            this.adapters.Add(adapter); // Add it to ArrayList adapter

        }
    }

The only problem is that the name of an adapter obtained this way will possibly differ from the instance name needed to create a performance counter. On my machine, this name is "Intel(R) PRO/100 VE Network Connection" querying WMI, and "Intel[R] Pro_100 VE Network Connection" in the performance console. I did not find a better solution and finally gave up WMI.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPL)

About the Author

Echevil


Member

Occupation: Software Developer
Company: Gemalto
Location: Singapore Singapore

Other popular Hardware & System articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 38 (Total in Forum: 38) (Refresh)FirstPrevNext
GeneralPerformance Counter not working on some PCs PinmemberOnlymeDavid9:51 1 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberEchevil20:44 1 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberOnlymeDavid9:22 2 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberEchevil17:15 2 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberOnlymeDavid20:18 2 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberEchevil3:24 3 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberOnlymeDavid20:29 3 Oct '07  
GeneralRe: Performance Counter not working on some PCs PinmemberEchevil21:18 3 Oct '07  
AnswerRe: Performance Counter not working on some PCs [modified] PinmemberPawJershauge6:41 23 Dec '07  
GeneralEchevil DLL source code need PinmemberNaseer Ahmad5:01 19 Jun '07  
GeneralRe: Echevil DLL source code need PinmemberEchevil14:52 19 Jun '07  
GeneralCool Pinmemberyellodoo6:55 4 Jan '07  
QuestionMemory Usage PinmemberMentoss7:19 27 Dec '06  
AnswerRe: Memory Usage PinmemberEchevil21:12 6 Jan '07  
QuestionWhat about Wireless networkcards? PinmemberLasse Rasch3:50 9 Dec '06  
AnswerRe: What about Wireless networkcards? PinmemberEchevil2:18 10 Dec '06  
Generalwild card? Pinmembercrazytri12:25 6 Dec '06  
Generalwhat about of connection measurment with ASP.NET Pinmembergeo-geo3:38 2 Nov '06  
Generalthank you very much Pinmemberosamahamed12323:35 3 Mar '06  
GeneralMonitoring Network Speed - WMI PinmemberkoenV3:31 22 Feb '06  
GeneralRe: Monitoring Network Speed - WMI Pinmemberwojwal2:00 5 Jan '07  
GeneralWhat About win98? PinmemberNassosReyzidis1:10 1 Jun '05  
GeneralRe: What About win98? PinmemberEchevil (Pang Chen)23:38 2 Nov '05  
GeneralRe: What About win98? PinmemberBikash Rai22:50 20 Dec '05  
GeneralRe: What About win98? PinmemberEchevil23:30 20 Dec '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Feb 2004
Editor: Smitha Vijayan
Copyright 2004 by Echevil
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project