James Toporipo Banda
James Toporipo Banda

Reputation: 27

Bandwidth monitoring system

I am trying to monitor the traffic of my internet connection i.e. the average speed at a given time, to get the average speed. I have tried this code but its not working. Where I am going wrong?

Function bwmonitor()
    Dim pc As New PerformanceCounterCategory("Network Interface")
    Dim instance As String = pc.GetInstanceNames(0)
    Dim bs As New PerformanceCounter("Network Interface", "Bytes Sent/sec", instance)
    Dim br As New PerformanceCounter("Network Interface", "Bytes Received/Sec", instance)
    Dim k As Integer = 0

    Do
        k = k + 1
        Dim kbsent As Integer = bs.NextValue() / 1024
        Dim kbRecieved As Integer = br.NextValue / 1024
        TextBox10.Text = kbsent
        TextBox11.Text = kbRecieved
        Threading.Thread.Sleep(1000)
    Loop Until k = 10

    Return 0
End Function

I have called the function but the textboxes are returning zeros only.

Upvotes: 1

Views: 6171

Answers (1)

GJKH
GJKH

Reputation: 1725

You'll need to find which network interface your using, create a console application with the code below and you'll be able to see which interface is active.

Also, you won't be able to update the UI in that manner, you'll need to use a background worker to have a rolling update in your text-boxes.

Sub Main()

Dim networkInterfaces As New  System.Diagnostics.PerformanceCounterCategory("Network Interface")
    Dim nics As String() = networkInterfaces.GetInstanceNames()
    Dim bytesSent(nics.Length - 1) As System.Diagnostics.PerformanceCounter
    Dim bytesReceived(nics.Length - 1) As System.Diagnostics.PerformanceCounter
    Dim i As Integer
    For i = 0 To nics.Length - 1
  bytesSent(i) = New System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", nics(i), True) 
  bytesReceived(i) = New System.Diagnostics.PerformanceCounter("Network Interface", "Bytes received/sec", nics(i), True) 
Next 
    'Dim ni As System.Diagnostics.PerformanceCounter 
For i = 0 To nics.Length - 1 
  System.Console.WriteLine(String.Format("     interface {0}: {1} ", i, nics(i))) 
Next 
Do 
        For i = 0 To nics.Length - 1
            System.Console.WriteLine(String.Format("     interface {0}: {1} bytes sent/sec, {2} bytes received/sec.  ", i, bytesSent(i).NextValue, bytesReceived(i).NextValue))
        Next

        System.Console.WriteLine("")
        System.Console.WriteLine("")
        System.Threading.Thread.Sleep(3000)
Loop 

End Sub

Upvotes: 1

Related Questions