Click here to Skip to main content
15,881,715 members
Articles / Programming Languages / C#
Article

Monitoring network speed

Rate me:
Please Sign up or sign in to vote.
4.79/5 (47 votes)
29 Feb 2004GPL31 min read 376.6K   30.7K   174   49
Detecting upload and download speed of a network adapter using performance counters.

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:

C#
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.

C#
/// <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:

C#
///
/// 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 (GPLv3)


Written By
Software Developer Autodesk
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNetwork information Pin
Surya Ayyagari29-Jul-09 1:57
Surya Ayyagari29-Jul-09 1:57 
GeneralPerformance Counter not working on some PCs Pin
OnlymeDavid1-Oct-07 8:51
OnlymeDavid1-Oct-07 8:51 
GeneralRe: Performance Counter not working on some PCs Pin
Chen Pang1-Oct-07 19:44
Chen Pang1-Oct-07 19:44 
GeneralRe: Performance Counter not working on some PCs Pin
OnlymeDavid2-Oct-07 8:22
OnlymeDavid2-Oct-07 8:22 
GeneralRe: Performance Counter not working on some PCs Pin
Chen Pang2-Oct-07 16:15
Chen Pang2-Oct-07 16:15 
GeneralRe: Performance Counter not working on some PCs Pin
OnlymeDavid2-Oct-07 19:18
OnlymeDavid2-Oct-07 19:18 
GeneralRe: Performance Counter not working on some PCs Pin
Chen Pang3-Oct-07 2:24
Chen Pang3-Oct-07 2:24 
GeneralRe: Performance Counter not working on some PCs Pin
OnlymeDavid3-Oct-07 19:29
OnlymeDavid3-Oct-07 19:29 
GeneralRe: Performance Counter not working on some PCs Pin
Chen Pang3-Oct-07 20:18
Chen Pang3-Oct-07 20:18 
AnswerRe: Performance Counter not working on some PCs [modified] Pin
Paw Jershauge23-Dec-07 5:41
Paw Jershauge23-Dec-07 5:41 
GeneralEchevil DLL source code need Pin
Naseer Ahmad19-Jun-07 4:01
Naseer Ahmad19-Jun-07 4:01 
GeneralRe: Echevil DLL source code need Pin
Chen Pang19-Jun-07 13:52
Chen Pang19-Jun-07 13:52 
GeneralCool Pin
yellodoo4-Jan-07 5:55
yellodoo4-Jan-07 5:55 
QuestionMemory Usage Pin
Mentoss27-Dec-06 6:19
Mentoss27-Dec-06 6:19 
AnswerRe: Memory Usage Pin
Chen Pang6-Jan-07 20:12
Chen Pang6-Jan-07 20:12 
QuestionWhat about Wireless networkcards? Pin
Lasse Rasch9-Dec-06 2:50
Lasse Rasch9-Dec-06 2:50 
AnswerRe: What about Wireless networkcards? Pin
Chen Pang10-Dec-06 1:18
Chen Pang10-Dec-06 1:18 
Questionwild card? Pin
crazytri6-Dec-06 11:25
crazytri6-Dec-06 11:25 
Questionwhat about of connection measurment with ASP.NET Pin
geo-geo2-Nov-06 2:38
geo-geo2-Nov-06 2:38 
Generalthank you very much Pin
osamahamed1233-Mar-06 22:35
osamahamed1233-Mar-06 22:35 
GeneralMonitoring Network Speed - WMI Pin
koenV22-Feb-06 2:31
koenV22-Feb-06 2:31 
GeneralRe: Monitoring Network Speed - WMI Pin
wojwal5-Jan-07 1:00
wojwal5-Jan-07 1:00 
QuestionWhat About win98? Pin
NassosReyzidis1-Jun-05 0:10
NassosReyzidis1-Jun-05 0:10 
AnswerRe: What About win98? Pin
Chen Pang2-Nov-05 22:38
Chen Pang2-Nov-05 22:38 
GeneralRe: What About win98? Pin
HakunaMatada20-Dec-05 21:50
HakunaMatada20-Dec-05 21:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.