Mohamed Mansour's Personal Website
Articles
How to calculate network bandwidth speed in c#
Posted on February 6, 2008, 2:47 am EST
If your wondering how fast your internet is in C#, there is an easy way to find out by using the NetworkInterface class in .NET. I will show the code and present a simple application on how to find your current upload and download speed .
How does it work?
That is quite simple! Each NetworkInterface component has an interface statistics object which provides statistical data for a network interface on the local computer. Depends which Internet Protocol your using (IPv4 or IPv6) you can easily grab that info! To do this in C# we do the following:
CODE:
IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();
From that object, we can fetch the BytesSent and BytesReceived from that network interface. By creating a simple timer that handles each tick rate in each 1sec interval, we can find the speed of bytes per second by finding the difference between the new bytes with respect to the previous ones. To make it more readable, we could convert bytes into kilobytes by dividing by 1024.
CODE:
// Globally declare these
int bytesSentSpeed = 0;
int bytesReceivedSpeed = 0;
// Grab speed in KB /s
bytesSentSpeed = (int)(interfaceStats.BytesSent - bytesSentSpeed ) / 1024;
bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - bytesReceivedSpeed ) / 1024;
That is it! That is how you make your own Bandwidth Meter in .NET. Take a look at my previous blog post on how to create a more sophisticated Windows timer that depends on kernel CPU tick time instead of .net. It requires interoping Kernel32.dll but you will have more precise statistics than using the Windows.Forms.Timer. The difference is very significant. Windows.Forms.Timer runs at 1 second resolution while the Kernel resolution is 10 msec! That is a huge difference and will make your results more exact!
Final code
CODE:
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace InterfaceTrafficWatch
{
/// <summary>
/// Network Interface Traffic Watch
/// by Mohamed Mansour
///
/// Free to use under GPL open source license!
/// </summary>
public partial class MainForm : Form
{
/// <summary>
/// Timer Update (every 1 sec)
/// </summary>
private const double timerUpdate = 1000;
/// <summary>
/// Interface Storage
/// </summary>
private NetworkInterface[] nicArr;
/// <summary>
/// Main Timer Object
/// (we could use something more efficient such
/// as interop calls to HighPerformanceTimers)
/// </summary>
private Timer timer;
/// <summary>
/// Constructor
/// </summary>
public MainForm()
{
InitializeComponent();
InitializeNetworkInterface();
InitializeTimer();
}
/// <summary>
/// Initialize all network interfaces on this computer
/// </summary>
private void InitializeNetworkInterface()
{
// Grab all local interfaces to this computer
nicArr = NetworkInterface.GetAllNetworkInterfaces();
// Add each interface name to the combo box
for (int i = 0; i < nicArr.Length; i++)
cmbInterface.Items.Add(nicArr[i].Name);
// Change the initial selection to the first interface
cmbInterface.SelectedIndex = 0;
}
/// <summary>
/// Initialize the Timer
/// </summary>
private void InitializeTimer()
{
timer = new Timer();
timer.Interval = (int)timerUpdate;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
/// <summary>
/// Update GUI components for the network interfaces
/// </summary>
private void UpdateNetworkInterface()
{
// Grab NetworkInterface object that describes the current interface
NetworkInterface nic = nicArr[cmbInterface.SelectedIndex];
// Grab the stats for that interface
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
// Calculate the speed of bytes going in and out
// NOTE: we could use something faster and more reliable than Windows Forms Tiemr
// such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html
int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(lblBytesSent.Text)) / 1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(lblBytesReceived.Text)) / 1024;
// Update the labels
lblSpeed.Text = nic.Speed.ToString();
lblInterfaceType.Text = nic.NetworkInterfaceType.ToString();
lblSpeed.Text = nic.Speed.ToString();
lblBytesReceived.Text = interfaceStats.BytesReceived.ToString();
lblBytesSent.Text = interfaceStats.BytesSent.ToString();
lblUpload.Text = bytesSentSpeed.ToString() + " KB/s";
lblDownload.Text = bytesReceivedSpeed.ToString() + " KB/s";
}
/// <summary>
/// The Timer event for each Tick (second) to update the UI
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void timer_Tick(object sender, EventArgs e)
{
UpdateNetworkInterface();
}
}
}
Download
The Project Source Code: here
