Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Using C# to Monitor Bandwidth for Wireless Devices Using NetworkInterface and .NET LINQ

Rate me:
Please Sign up or sign in to vote.
4.92/5 (10 votes)
19 Nov 2012CPOL1 min read 53.6K   3.8K   40   10
Using C# to monitor the bandwidth for wireless devices.

Introduction  

This article explains creating a simple tool which will display the current bandwidth and other meta information about a selected wireless network card attached to your machine. If multiple wireless cards are attached to the machine then the tool has the ability to detect all of them. And the user can select which card we are interested in monitoring. Moreover this tool can be expanded to work with Ethernet adapters as well.   

Background  

.NET allows you to access all the network interface card information via the NetworkInterface.GetAllNetworkInterfaces() method. By applying LINQ filtering we can filter the information to capture only wireless interface information. Afterwards it’s just manipulating the inbuilt properties.

The code in this tool will help you calculate the number of bytes sent by the wireless device. And to measure the current download speed of your selected wireless adaptor along with it you will be able to gain access to the IP address associated with the wireless interface using the UnicastIPAddressInformation class.

Using the Code  

The first thing that we have do is detect all the wireless devises available in your machine and populate them into the dropdownbox:

C#
using System.Net.NetworkInformation;

/// Detecting Wireless Adaptors Using Linq
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
  network => network.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
 
////Modified by to select only the active wireless adaptor by using below Linq statement
////.Where(network => network.OperationalStatus == 
//  OperationalStatus.Up && network.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)

////To detect all Ethernet and wireless adaptors you can use below statement 
////.Where(network => network.OperationalStatus == OperationalStatus.Up && 
//  (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet || 
//   network.NetworkInterfaceType == NetworkInterfaceType.Wireless80211))

///Add Items To Drop Down List
cmbAdptors.DisplayMember = "Description";
cmbAdptors.ValueMember= "Id";
foreach (NetworkInterface item in nics)
{
   cmbAdptors.Items.Add(item);
}
if (cmbAdptors.Items.Count > 0)
    cmbAdptors.SelectedIndex = 0;

Once the user changes the devises or initially when the first device is selected the selected index change event will fire and we can capture the IP address and then call the BandwidthCalculator method. In addition we need to start the timer which will update information every second:

C#
private void cmbAdptors_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (cmbAdptors.SelectedItem is NetworkInterface)
        {
            slectedNic = cmbAdptors.SelectedItem as NetworkInterface;
             uniCastIPInfo = null;
            ///Populating IPv4 address
            if (slectedNic != null && slectedNic.GetIPProperties().UnicastAddresses != null)
            {
                UnicastIPAddressInformationCollection ipInfo = slectedNic.GetIPProperties().UnicastAddresses;

                foreach (UnicastIPAddressInformation item in ipInfo)
                {
                    if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        lblIP.Text = item.Address.ToString();
                        uniCastIPInfo = item;                            
                        break;
                    }
                }
            }

            BandwidthCalculator(uniCastIPInfo, slectedNic);
            wirelssUpdator.Enabled = true;
        }

    }
    catch (Exception ex)
    {               
        throw;
    }
}

The BandwidthCalculator method which will perform the updates:

C#
public void BandwidthCalculator(UnicastIPAddressInformation ipInfo , NetworkInterface selecNic)
{
    try
    {
        if (selecNic == null)
            return;
        //Setting General Information 
        lblType.Text = selecNic.NetworkInterfaceType.ToString();
        lblOp.Text = selecNic.OperationalStatus.ToString();


       IPv4InterfaceStatistics interfaceData = selecNic.GetIPv4Statistics();
        int bytesRecivedSpeedValue = (int)(interfaceData.BytesReceived - double.Parse(lblReceived.Text)) / 1024;
        lblReceived.Text = interfaceData.BytesReceived.ToString();
        lblSpeed.Text = bytesRecivedSpeedValue.ToString() + "KB/s";//Download speed
        if (ipInfo != null)
        {
            TimeSpan addressLifeTime = TimeSpan.FromSeconds(ipInfo.AddressValidLifetime);
            lblVallifetime.Text = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms",
                                   addressLifeTime.Hours,
                                   addressLifeTime.Minutes,
                                   addressLifeTime.Seconds,
                                   addressLifeTime.Milliseconds);

        }
    }
    catch (Exception ex)
    {

    }

}

Updating the timer:

C#
private void wirelssUpdator_Tick(object sender, EventArgs e)
{
    BandwidthCalculator(uniCastIPInfo, slectedNic);
}

Points of Interest

You can extend this application to work with the below interface types 

  • Wireless80211
  • Ethernet 
  • MobileBroadbandGSM 
  • MobileBroadbandCDMA
  • etc.. 

Points to Remember 

Make sure that you are using .NET 3.5 or higher. Also you will need at least one wireless interface attached to your system.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionOnly select one running application? Pin
Member 1089452119-Jun-14 1:18
Member 1089452119-Jun-14 1:18 
Questionwired Network Pin
usha C2-Jul-13 23:09
usha C2-Jul-13 23:09 
QuestionWiFi devices connected to an AP Pin
vsrinivas20841-Jul-13 1:53
vsrinivas20841-Jul-13 1:53 
QuestionPerformanceCounter Pin
giammin25-Nov-12 23:45
giammin25-Nov-12 23:45 
GeneralMy vote of 5 Pin
pradiprenushe27-Aug-12 2:57
professionalpradiprenushe27-Aug-12 2:57 
GeneralMy vote of 5 Pin
Christian Amado22-Aug-12 5:11
professionalChristian Amado22-Aug-12 5:11 
GeneralMy vote of 5 Pin
Debdatta Basu21-Aug-12 23:00
Debdatta Basu21-Aug-12 23:00 
QuestionBytes Received or Sent? Pin
andegre20-Aug-12 15:52
andegre20-Aug-12 15:52 
Am I delirious, I'm reading that code and it tells me that the DownloadSpeed is actually the upload speed, is that correct?
AnswerRe: Bytes Received or Sent? Pin
Tyronne Thomas20-Aug-12 16:28
Tyronne Thomas20-Aug-12 16:28 
GeneralNice Pin
Júnior Pacheco17-Aug-12 4:08
professionalJúnior Pacheco17-Aug-12 4:08 

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.