Getting IPv4 Bytes Sent and Received from NICs on a PC or Server

I recently had a need to track the data usage on a number of Hyper-V virtual machines for billing hosting customers. There was nothing cheap and easy in the marketplace so as a developer always does, I wrote one myself. The whole app consists of an ASP.NET Web Service, a .NET Windows Service and an ASP.NET web app for the reporting/charting but I thought I’d share a small part of the code.

I found it hard to find good examples on the web of how to do it so it took a fair amount of time to find the right objects to do the job. In the end the code proved quite easy. This is a very cut down version of the function that deals with getting the bytes sent and received.

Dim NICList() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Dim NICStats As IPv4InterfaceStatistics

Dim NetworkName As String
Dim BytesSent As Double = 0
Dim BytesReceived As Double = 0

For Each NIC As NetworkInterface In NICList
    If NIC.OperationalStatus = OperationalStatus.Up And NIC.NetworkInterfaceType = NetworkInterfaceType.Ethernet Then
        NetworkName = NIC.Name
        NICStats = NIC.GetIPv4Statistics
        BytesReceived = NICStats.BytesReceived
        BytesSent = NICStats.BytesSent

        'Do Something with the data here
    End If

You then have to figure a way to track the data usage over a period of time as this just gives you a since last reboot figure. Each implementation of these requirements will differ so I won’t go any further into my solution.

The biggest issue I found with this method is that there is no way to track a specific connection. You can’t use the network name because that can change at any time and although using the MAC address would work on physical servers, it won’t work on VM’s because the MAC can change. At the moment I’m just recording it by name but I’m looking for a better answer.