Criando o testador de Internet
Autor: MCSE - Inaldo Barros Jr | Publicado: 2014-02-19T05:58:00-08:00

<span title="How does it work?

">Como isso funciona ?Isso é muito simples ! Cada
 componente tem um objeto NetworkInterface estatísticas de interface que
 fornece dados estatísticos para uma interface de rede no computador 
local. Depende que Internet Protocol seu uso (IPv4 ou IPv6 ), você pode facilmente pegar essa informação ! <span title="To do this in C# we do the following:

">Para fazer isso em C # que faça o seguinte:<span title="CODE:
">CODE:<span title="IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();

">. IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetAllNetworkInterfaces ( ) [ 0 ] GetIPv4Statistics ( ) ;A partir desse objeto , podemos buscar o BytesSent e BytesReceived de que a interface de rede. Através
 da criação de um temporizador simples que manipula cada taxa de carraça
 em cada intervalo de 1 seg , podemos encontrar a velocidade de bytes 
por segundo por encontrar a diferença entre os novos bytes com respeito 
aos anteriores . <span title="To make it more readable, we could convert bytes into kilobytes by dividing by 1024.

">Para torná-lo mais legível , poderíamos converter bytes em kilobytes , dividindo por 1024 .<span title="CODE:
">CODE:<span title="// Globally declare these
">/ / Globalmente declarar estes últimos<span title="int bytesSentSpeed = 0;
">int bytesSentSpeed ​​= 0 ;<span title="int bytesReceivedSpeed = 0;

">int bytesReceivedSpeed ​​= 0 ;<span title="// Grab speed in KB /s
">/ / Velocidade Grab em KB / s<span title="bytesSentSpeed = (int)(interfaceStats.BytesSent - bytesSentSpeed ) / 1024;
">bytesSentSpeed ​​= (int ) ( interfaceStats.BytesSent - bytesSentSpeed ​​) / 1024;<span title="bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - bytesReceivedSpeed ) / 1024;

">bytesReceivedSpeed ​​= (int ) ( interfaceStats.BytesReceived - bytesReceivedSpeed ​​) / 1024;Isso é que é ! Isso é como você fazer o seu próprio medidor de largura de banda em . NET . Dê
 uma olhada no meu post anterior sobre como criar um ambiente mais 
sofisticado temporizador do Windows que depende do kernel CPU carrapato 
tempo em vez de. Net. Exige interoping Kernel32.dll , mas você vai ter estatísticas mais precisas do que usando o Windows.Forms.Timer . A diferença é muito significativa . Windows.Forms.Timer funciona a resolução de 1 segundo , enquanto a resolução Kernel é de 10 milissegundos ! <span title="That is a huge difference and will make your results more exact!
">Essa é uma grande diferença e fará com que seus resultados mais exato!<span title="Final code

">código final<span title="CODE:
">CODE:<span title="using System;
">using System;<span title="using System.Net.NetworkInformation;
">usando System.Net.NetworkInformation ;<span title="using System.Windows.Forms;

">using System.Windows.Forms;<span title="namespace InterfaceTrafficWatch
">namespace InterfaceTrafficWatch<span title="{
    ">{&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
    ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Network Interface Traffic Watch
    ">/ / / Rede Interface Traffic Assista&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// by Mohamed Mansour
    ">/ / / Por Mohamed Mansour&nbsp;&nbsp;&nbsp;&nbsp;<span title="///
    ">/ / /&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Free to use under GPL open source license!
    ">/ / / Livre para usar sob a GPL licença open source!&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
    ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;<span title="public partial class MainForm : Form
    ">MainForm público classe parcial : Form&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
        ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Timer Update (every 1 sec)
        ">/ / Update / Timer ( a cada 1 seg)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private const double timerUpdate = 1000;

        ">private const timerUpdate duplo = 1000;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Interface Storage
        ">/ / / Interface de Armazenamento&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private NetworkInterface[] nicArr;

        ">NetworkInterface privado [] nicArr ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Main Timer Object
        ">/ / / Main Temporizador objeto&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// (we could use something more efficient such
        ">/ / / ( Que poderia usar algo mais eficiente como&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// as interop calls to HighPerformanceTimers)
        ">/ / / Como chamadas de interoperabilidade para HighPerformanceTimers )&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private Timer timer;

        ">private Timer timer ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Constructor
        ">/ / / Construtor&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="public MainForm()
        ">MainForm pública ()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
            ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="InitializeComponent();
            ">InitializeComponent ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="InitializeNetworkInterface();
            ">InitializeNetworkInterface ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="InitializeTimer();
        ">InitializeTimer ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="}

        ">}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Initialize all network interfaces on this computer
        ">/ / / Inicializar todos os interfaces de rede neste computador&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private void InitializeNetworkInterface()
        ">InitializeNetworkInterface private void ()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
            ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Grab all local interfaces to this computer
            ">/ / Pegue todas as interfaces locais para este computador&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="nicArr = NetworkInterface.GetAllNetworkInterfaces();

            ">nicArr NetworkInterface.GetAllNetworkInterfaces = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Add each interface name to the combo box
            ">/ / Adiciona o nome de cada interface para caixa de combinação&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="for (int i = 0; i &lt; nicArr.Length; i++)
                ">for (int i = 0; i &lt; nicArr.Length ; i + +)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="cmbInterface.Items.Add(nicArr[i].Name);

            ">cmbInterface.Items.Add ( . nicArr [i ] Nome );&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Change the initial selection to the first interface
            ">/ / Muda a seleção inicial para a primeira interface&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="cmbInterface.SelectedIndex = 0;
        ">cmbInterface.SelectedIndex = 0 ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="}

        ">}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Initialize the Timer
        ">/ / / Inicializar o Temporizador&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private void InitializeTimer()
        ">private void InitializeTimer ()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
            ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="timer = new Timer();
            ">timer = new Timer ();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="timer.Interval = (int)timerUpdate;
            ">Timer.Interval = (int) timerUpdate ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="timer.Tick += new EventHandler(timer_Tick);
            ">Timer.Tick + = new EventHandler ( timer_Tick );&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="timer.Start();
        ">timer.Start ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="}

        ">}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// Update GUI components for the network interfaces
        ">Componentes / / / Update GUI para as interfaces de rede&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="private void UpdateNetworkInterface()
        ">UpdateNetworkInterface private void ()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
            ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Grab NetworkInterface object that describes the current interface
            ">/ / Object Grab NetworkInterface que descreve a interface atual&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="NetworkInterface nic = nicArr[cmbInterface.SelectedIndex];

            ">NetworkInterface nic = nicArr [ cmbInterface.SelectedIndex ];&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Grab the stats for that interface
            ">/ / Pega as estatísticas de que a interface&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();

            ">IPv4InterfaceStatistics interfaceStats nic.GetIPv4Statistics = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Calculate the speed of bytes going in and out
            ">/ / Calcular a velocidade de bytes que entram e saem&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// NOTE: we could use something faster and more reliable than Windows Forms Tiemr
            ">/ / NOTA: nós poderíamos usar algo mais rápido e mais confiável do que o Windows Forms Tiemr&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html
            ">/ / Tal como HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(lblBytesSent.Text)) / 1024;
            ">int bytesSentSpeed ​​= (int ) ( interfaceStats.BytesSent - Double.Parse ( lblBytesSent.Text )) / 1024;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(lblBytesReceived.Text)) / 1024;

            ">int bytesReceivedSpeed ​​= (int ) ( interfaceStats.BytesReceived - Double.Parse ( lblBytesReceived.Text )) / 1024;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="// Update the labels
            ">/ / Atualiza os rótulos&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblSpeed.Text = nic.Speed.ToString();
            ">lblSpeed.Text nic.Speed.ToString = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblInterfaceType.Text = nic.NetworkInterfaceType.ToString();
            ">lblInterfaceType.Text nic.NetworkInterfaceType.ToString = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblSpeed.Text = nic.Speed.ToString();
            ">lblSpeed.Text nic.Speed.ToString = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblBytesReceived.Text = interfaceStats.BytesReceived.ToString();
            ">lblBytesReceived.Text interfaceStats.BytesReceived.ToString = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblBytesSent.Text = interfaceStats.BytesSent.ToString();
            ">lblBytesSent.Text interfaceStats.BytesSent.ToString = ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblUpload.Text = bytesSentSpeed.ToString() + &quot; KB/s&quot;;
            ">lblUpload.Text = bytesSentSpeed.ToString ( ) + " KB / s";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="lblDownload.Text = bytesReceivedSpeed.ToString() + &quot; KB/s&quot;;

        ">lblDownload.Text = bytesReceivedSpeed.ToString ( ) + " KB / s";&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="}

        ">}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;summary&gt;
        ">/ / / &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// The Timer event for each Tick (second) to update the UI
        ">/ / / O evento timer para cada Tick ( segunda ) para atualizar a interface do usuário&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;/summary&gt;
        ">/ / / &lt;/ Summary&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;param name=&quot;sender&quot;&gt;&lt;/param&gt;
        ">/ / /  &lt;/ param&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="/// &lt;param name=&quot;e&quot;&gt;&lt;/param&gt;
        ">/ / /  &lt;/ param&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="void timer_Tick(object sender, EventArgs e)
        ">vazio timer_Tick (object sender, EventArgs e)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="{
            ">{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="UpdateNetworkInterface();
        ">UpdateNetworkInterface ( ) ;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span title="}

    ">}&nbsp;&nbsp;&nbsp;&nbsp;<span title="}
">}}

Baixe aqui : http://www.m0interactive.com/download/10.00