Network Bandwidth Monitor [VB.NET]

Network Bandwidth Monitor


Screen Shot 
Download Source Code Link



NetworkBandwidth.vb
Imports System.Text.RegularExpressions
Imports System.Net.NetworkInformation

Public Class NetworkBandwidth
    Private Adapters As NetworkInterface()

    Public Sub New() 'Constructer

    End Sub

    Public Function GetNetInteface() As List(Of NetworkInterface)
        Adapters = NetworkInterface.GetAllNetworkInterfaces
        Dim NetList As New List(Of NetworkInterface)
        Dim NetInterfaceFilter As NetworkInterfaceType() = {NetworkInterfaceType.Ethernet, NetworkInterfaceType.Ppp, NetworkInterfaceType.Wireless80211}
        For Each adapter As NetworkInterface In Adapters
            If inArrayNetType(NetInterfaceFilter, adapter.NetworkInterfaceType) Then
                NetList.Add(adapter)
            End If
        Next
        Return NetList
    End Function

    Private Function inArrayNetType(ByVal arr As NetworkInterfaceType(), ByVal match As NetworkInterfaceType) As Boolean
        For Each nettype As NetworkInterfaceType In arr
            If nettype = match Then
                Return True
            End If
        Next
        Return False
    End Function

    Public Function GetExtIpAddr() As String
        Try
            Dim ExternalIP As String
            ExternalIP = (New Net.WebClient()).DownloadString("http://checkip.dyndns.org/")
            ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
                         .Matches(ExternalIP)(0).ToString()

            Return ExternalIP
        Catch
            Return "No Connection"
        End Try
    End Function


End Class

mainForm.vb
Imports System.Net.NetworkInformation
Imports System.Text.RegularExpressions
Imports System.Net

Public Class mainForm

    Dim Adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
    Private CurrentNetworkInterface As NetworkInterface

    Private InitNicStats As Boolean = False
    Delegate Sub FuncCallback(ByRef obj As Object, ByVal text As String)
    Dim Thread As Threading.Thread = Nothing
    Dim NetworkBW As New NetworkBandwidth
    Event NetChangedHandler As NetworkInformation.NetworkAvailabilityChangedEventHandler

    Private Sub mainForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            Thread.Abort()
        Catch ex As Exception
        End Try
    End Sub

    Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadNicComboBox()

        Thread = New Threading.Thread(AddressOf UpdateExtIpAddr)
        Thread.IsBackground = True
        Thread.Start()

        AddHandler NetworkChange.NetworkAvailabilityChanged, AddressOf OnNetWorkChanged_Event
        AddHandler NetworkChange.NetworkAddressChanged, AddressOf OnNetworkAddrChanged_Event
    End Sub

    Private Sub LoadNicComboBox()
        Adapters = NetworkInterface.GetAllNetworkInterfaces
        Dim NetInterfaceFilter As NetworkInterfaceType() = {NetworkInterfaceType.Ethernet, NetworkInterfaceType.Ppp, NetworkInterfaceType.Wireless80211}
        If NICComboBox.InvokeRequired Then
            Dim d As New FuncCallback(AddressOf LoadNicComboBox)
            Me.Invoke(d, New Object() {Nothing, Nothing})
            'Invoke(New MethodInvoker(AddressOf LoadNicComboBox))
        Else
            NICComboBox.DataSource = NetworkBW.GetNetInteface
            NICComboBox.DisplayMember = "Name"
            NICComboBox.ValueMember = "Id"
        End If

    End Sub

    Private Function inArrayNetType(ByVal arr As NetworkInterfaceType(), ByVal match As NetworkInterfaceType) As Boolean
        For Each nettype As NetworkInterfaceType In arr
            If nettype = match Then
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub NICComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NICComboBox.SelectedIndexChanged
        CurrentNetworkInterface = NICComboBox.SelectedItem

        Dim IpInterface As IPInterfaceProperties = CurrentNetworkInterface.GetIPProperties
        Dim UnicastIpaddr As UnicastIPAddressInformationCollection = IpInterface.UnicastAddresses
        If UnicastIpaddr.Count > 1 Then
            IpaddrLabel.Text = UnicastIpaddr(1).Address.ToString
        Else
            IpaddrLabel.Text = UnicastIpaddr(0).Address.ToString
        End If

        'UploadLabel.Text = BytesConverter(NicStats.BytesSent)
        'DownloadLabel.Text = BytesConverter(NicStats.BytesReceived)
        InitNicStats = False
    End Sub

    Public Function BytesConverter(ByVal bytes As Integer) As String
        Dim KB As Integer = 1024
        Dim MB As Integer = KB * KB
        Dim GB As Integer = KB * KB * KB
        Dim returnVal As String = "0 Bytes"

        Select Case bytes
            Case Is <= KB
                returnVal = bytes & " Bytes"
            Case Is > GB
                returnVal = (bytes / KB / KB / KB).ToString("0.00") & " KB"
            Case Is > MB
                returnVal = (bytes / KB / KB).ToString("0.00") & " MB"
            Case Is > KB
                returnVal = (bytes / KB).ToString("0.00") & " KB"
        End Select

        Return returnVal.ToString
    End Function

    Private Sub BandwidthPerSec()
        Try
            Dim NicStats As IPv4InterfaceStatistics = NICComboBox.SelectedItem.GetIPv4Statistics
            Static LastUpload As Integer = NicStats.BytesSent
            Static LastDownload As Integer = NicStats.BytesReceived

            If InitNicStats = True Then
                Dim Up = NicStats.BytesSent - LastUpload
                Dim Down = NicStats.BytesReceived - LastDownload

                UploadLabel.Text = BytesConverter(If(Up < 0, 0, Up)) & "/s"
                DownloadLabel.Text = BytesConverter(If(Down < 0, 0, Down)) & "/s"
            End If
            LastUpload = NicStats.BytesSent
            LastDownload = NicStats.BytesReceived

            TotalUploadLabel.Text = BytesConverter(NicStats.BytesSent)
            TotalDLLabel.Text = BytesConverter(NicStats.BytesReceived)

            InitNicStats = True
        Catch ex As Exception
            'BandwidthUpdateTimer.Stop()
            'MsgBox(ex.ToString)
        End Try

    End Sub

    Private Sub BandwidthUpdateTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BandwidthUpdateTimer.Tick
        If NICComboBox.SelectedIndex >= 0 Then
            BandwidthPerSec()
        End If
    End Sub

    Private Sub OnNetWorkChanged_Event(ByVal sender As Object, ByVal e As NetworkInformation.NetworkAvailabilityEventArgs) Handles Me.NetChangedHandler
        LoadNicComboBox()
    End Sub

    Private Sub OnNetworkAddrChanged_Event(ByVal sender As Object, ByVal e As EventArgs)
        LoadNicComboBox()
        'SetTextLabelDelegate(IpaddrLabel, "")
        Invoke(New MethodInvoker(Sub()
                                     Dim ip = (CType(NICComboBox.SelectedItem, NetworkInterface)).GetIPProperties.UnicastAddresses(0).Address.ToString
                                     IpaddrLabel.Text = ip
                                 End Sub))
    End Sub

    Private Sub UpdateExtIpAddr()
        'Dim ipaddr As String = NetworkBW.GetExtIpAddr
        If ExtIpLabel.InvokeRequired Then
            'Me.Invoke(New Action(Of String)(AddressOf UpdateExtIpAddr), IPAddr)
            Me.Invoke(New MethodInvoker(AddressOf UpdateExtIpAddr))
        Else
            ExtIpLabel.Text = NetworkBW.GetExtIpAddr
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        NICComboBox.DataSource = NetworkBW.GetNetInteface
    End Sub

    Private Sub RefreshIpLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles RefreshIpLinkLabel.LinkClicked
        Try
            If Not Thread.IsAlive Then
                Thread = New Threading.Thread(AddressOf UpdateExtIpAddr)
                Thread.IsBackground = True
                Thread.Start()
            End If
        Catch ex As Exception

        End Try
    End Sub


End Class

2 comments :

  1. Hi. very pleased to see the explanation. waiting for other interesting posts at a time when that will come.
    From bvba Woodstone

    ReplyDelete
  2. Thank you very much for this cool snippet. This may be One of the coolest VB Scripts I've seen and I appreciate you giving it out to us.

    ReplyDelete

Category

Other post

Recent Posts