C#C
C#3y ago
Suzz

network upload and download speed using System.Net.NetworkInformation package in .net core

the below is my code i've tried using System.Net.NetworkInformation libraray.

using System.Net.NetworkInformation;

var interfaces = NetworkInterface.GetAllNetworkInterfaces();

foreach (var networkInterface in interfaces)
    if (networkInterface.OperationalStatus == OperationalStatus.Up &&
        networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
        networkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
        networkInterface.NetworkInterfaceType != NetworkInterfaceType.Unknown && !networkInterface.IsReceiveOnly)
    {
        Console.WriteLine($"Monitoring network speed for interface: {networkInterface.Name}");
        var bytesSent = networkInterface.GetIPv4Statistics().BytesSent;
        var bytesReceived = networkInterface.GetIPv4Statistics().BytesReceived;
        long uploadSpeed = CalculateSpeed(bytesSent);
        long downloadSpeed = CalculateSpeed(bytesReceived);

        Console.WriteLine($"Bytes Sent: {bytesSent} bytes | Bytes Received: {bytesReceived} bytes");
        Console.WriteLine($"Upload Speed: {uploadSpeed} Mbps | Download Speed: {downloadSpeed} Mbps");
    }

Console.ReadKey();

static long CalculateSpeed(long bytes)
{
    const double bytesToMegabits = 8.0 / (1000 * 1000);
    return (long)(bytes * bytesToMegabits);
}



output is:

Monitoring network speed for interface: Wi-Fi
Bytes Sent: 46381565 bytes | Bytes Received: 1586958802 bytes
Upload Speed: 371 Mbps | Download Speed: 12695 Mbps
image.png
Was this page helpful?