Click here to Skip to main content
Email Password   helpLost your password?

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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralNetwork information
Surya Ayyagari
2:57 29 Jul '09  
Can I get this information for network PCs?
GeneralPerformance Counter not working on some PCs
OnlymeDavid
9:51 1 Oct '07  
Dear Sir,

I have tried the perfmon.exe, on almost all of the pc's at my college the "\\Network Interface\\Bytes Sent/Sec" counter is always showing 0,while it is showing proper values for the Bytes Received /Sec. While the same is working fine on my home pc, both use the same OS, i.e. winxp sp2.

and due to the counter not working, i am unable to fetch values in the app..... can you please tell me a way to enable those counters in perf mon ?
GeneralRe: Performance Counter not working on some PCs
Echevil
20:44 1 Oct '07  
I'm not sure what may be the cause. Maybe it has something to do with device driver. Do your pc's at your college share the same hardware configuration and use the same driver (possibly a non-standard one)?
GeneralRe: Performance Counter not working on some PCs
OnlymeDavid
9:22 2 Oct '07  
Some PC's use the same config, some uses diff. But i have no idea why onyl "Sent Bytes/Sec" is not working, rest of the counters are working fine. Any way to restart the perfmon service, and reset the counters, so that they can start, or any trouble shoot for it ?
GeneralRe: Performance Counter not working on some PCs
Echevil
17:15 2 Oct '07  
Then might it be some software you installed? I have no idea either, and I did not find any useful information on the internet concerning this problem. Sorry
GeneralRe: Performance Counter not working on some PCs
OnlymeDavid
20:18 2 Oct '07  
Thankyou sir, for very prompt reply.

Do you know any other way of how I can monitor the bandwidth (without the performance counters) in C#.NET 2005.
or can guide me to some links that i can refer. I have searched the .net and also codeproject, i was only able to find sample progs that used the ndis drivers, or the winpcap wrapper. I am not supposed to use them in my project at college. so if there is any other way, then it would really be apreciated.


GeneralRe: Performance Counter not working on some PCs
Echevil
3:24 3 Oct '07  
I believe you can do it with Windows Management Instrumentation (WMI). It is quite powerful though not so easy to use as performance counters. Lots of documentation are available in MSDN. I don't know any details now since I haven't written any code with these stuff for years.
GeneralRe: Performance Counter not working on some PCs
OnlymeDavid
20:29 3 Oct '07  
thanks m8 . I will surely try doing it using the WMI. But one question, doesn't WMI only give static info ? cause the Bandwidth will keep on changing. anyways, ill do search for these things in MSDN. thanks a lot once again Smile
GeneralRe: Performance Counter not working on some PCs
Echevil
21:18 3 Oct '07  
I can't guarantee that you can do it with WMI. But even with performance counters, the data I can obtain directly is packets sent/received so far. Just do some simple calculations.
AnswerRe: Performance Counter not working on some PCs [modified]
PawJershauge
6:41 23 Dec '07  
I know this comes a bit late.

But i had the same problem some months ago, and i just couldnt figure out the problem, but then i had to reinstall my PC, and after that the performance counter worked fine ???. so that got me thinking, what was the diffrens between now and then, ahhh but yes it was the Pagefile i had disabled, so i went into the computer properties, and disabled the PageFile, and wupti the program <u>didnt</u> work. So my conclusion was:

Pagefile Disabled = Performance Counter Disabled
Pagefile Enabled = Performance Counter Enabled

Dont ask me how or why, but its like that on my computer... hope it helps. Big Grin Big Grin
modified on Sunday, December 23, 2007 11:56:53 AM

GeneralEchevil DLL source code need
Naseer Ahmad
5:01 19 Jun '07  
Hi
i read your article it is much easy and understandable but there is no source code of Echevil DLL i want to review code.
please send me a source code of "Echevil DLL"
Thank So much
GeneralRe: Echevil DLL source code need
Echevil
14:52 19 Jun '07  
The code from the "Download Source" link is actually the source code of the dll.
GeneralCool
yellodoo
6:55 4 Jan '07  
Simple, easy to understand.. Thanks

Little Improvement Day by Day

QuestionMemory Usage
Mentoss
7:19 27 Dec '06  
Hello,
I noticed that the memory usage keeps rising when i update my form to show the download/upload speed (with timer). At first i thought it had something to do with my program but then i looked at the memory use of the NetworkMonitorDemo and it also keeps rising.
Any way to prevent this?
AnswerRe: Memory Usage
Echevil
21:12 6 Jan '07  
Hi
Sorry i didn't reply you sooner. The earthquake in Taiwan did cause some network connectivity problems.

The memory keeps rising because network speed is sampled with performance counter in a timely fashion, and this is something I have no control over. No explicit "Dispose" of any objects can be added.

Calling garbage collector helps but nothing can be guaranteed.
QuestionWhat about Wireless networkcards?
Lasse Rasch
3:50 9 Dec '06  
Hey!

I also like this article very much. However i can only get it to find my onboard network adapter. I have a Wireless D-Link USB network card. It can't seem to find that card.

Does anyone know why?


/Lasse
AnswerRe: What about Wireless networkcards?
Echevil
2:18 10 Dec '06  
As far as I can remember, normal wireless network cards work properly. If you know about the Performance monitor in windows, you may check the correspondent performance counter of your device there, and possibly make adaptions of the source code to support it.
Generalwild card?
crazytri
12:25 6 Dec '06  
Great article!
I was using the old Windows native PHD (Performance Data Helper) API's and it supports the wildcard (*) for network adapters. Took me a while to figure out that it doesn't work with .NET performanceCounter class (at least not with .NET 1.1)
Thanks for the tips.
Generalwhat about of connection measurment with ASP.NET
geo-geo
3:38 2 Nov '06  
As we know we cannot access Counters trough web page

winx
Generalthank you very much
osamahamed123
23:35 3 Mar '06  
its very good code but we want to know about dll
and is there aney code about download speed for each program
-- modified at 4:38 Saturday 4th March, 2006
GeneralMonitoring Network Speed - WMI
koenV
3:31 22 Feb '06  
I was very pleased to find your solution.
You gave up on WMI because of non-matching adapter-names with respect to the names needed by the PerformanceCounter.InstanceName member.

I experimented a little further and (empirically) found the following:
the name needed in the PerformanceCounter.InstanceName can be derived from the description property of a Win32_NetworkAdapterConfiguration WMI Object, by replacing any round brackets ('(', ')')by square ones ('[', ']') and any slants ('/') by underscores ('_').

On my desktop running XPProSP2:
WMI: "Intel(R) PRO/1000 PM Network Connection - Packet Scheduler Miniport"
PerformanceCounter: "Intel[R] PRO_1000 PM Network Connection - Packet Scheduler Miniport"
On my laptop running Win2K:
WMI: "IBM 10/100 EtherJet CardBus Adapter"
PerformanceCounter: "IBM 10_100 EtherJet CardBus Adapter"

I believe this is consistent with your observations.
Any confirmation OR counter-evidence would be largely appreciated!

KoenV
GeneralRe: Monitoring Network Speed - WMI
wojwal
2:00 5 Jan '07  
Well I'm trying to get into this also... And as my results confirms that only Win32_NetworkAdapterConfiguration - description field match there is more chars to replace. For example: '#' into '_':

WMI --> Karta Realtek RTL8139 Family PCI Fast Ethernet NIC #2
PerformanceCounter --> Karta Realtek RTL8139 Family PCI Fast Ethernet NIC _2

And there can be more special chars like (#,$,% ....) that changes into '_'...

I sbd will seek for solution let me only say that:
Win32_NetworkAdapterConfiguration - Caption - doesnt match at all
and
Win32_NetworkAdapter - Caption,Description,Name - also doesnt match at all



Wojciech Walek
GeneralWhat About win98?
NassosReyzidis
1:10 1 Jun '05  
Hi man,
excelent work on the library, efficient and quick But, what about win98? when i run the program in win98 OS the exception Suported only winNT!!.
Do you have any idea woh to overcome this issue?
thx
again great job.

GanDad
GeneralRe: What About win98?
Echevil (Pang Chen)
23:38 2 Nov '05  
yeah it does not work on win98
GeneralRe: What About win98?
Bikash Rai
22:50 20 Dec '05  
Any idea why it doesn't work with Win98? I would like a solution for Win98 and your article to meet the same but if i know why it doesn't work then maybe it would bw wasy for me. Blush

Bikash Rai


Last Updated 1 Mar 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010