Search code examples
c#networkingmobilewifisystem.net

How can I get "How many Network data(Mobile or WiFi) used when I call API in c# desktop application"


How can I get "How many Network data(Mobile or WiFi) used when I call API in c# desktop application" I want to know How can i get total used data when i call API service

I have done following code:

if (!NetworkInterface.GetIsNetworkAvailable())
    return;

NetworkInterface[] interfaces
    = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface ni in interfaces)
{
    Console.WriteLine("    Bytes Sent: {0}",
        ni.GetIPv4Statistics().BytesSent);
    Console.WriteLine("    Bytes Received: {0}",
        ni.GetIPv4Statistics().BytesReceived);
    lblCarrierCharge.Text = " Bytes Received: " + ni.GetIPv4Statistics().BytesReceived;
}

API CALL

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cloudEndpoint);
request.Method = "Get";
long inputLength = request.ContentLength;
long outputLength = 0;
string responseContent = "";

DateTime beginTimestamp = DateTime.Now;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Solution

  • To compute for the total bytes received per call. You'd want to save the current value of .GetIPv4Statistics().BytesReceived and then after your call, perform the same call and subtract the new value to the previous one.

    int previousNetworkBytesSent = 0;
    
    foreach (NetworkInterface ni in interfaces)
    {
        previousNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
    }
    
    // perform your call here
    
    int newNetworkBytesSent = 0;
    
    foreach (NetworkInterface ni in interfaces)
    {
        newNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
    }
    
    int totalBytesUsed = newNetworkBytesSent - previousNetworkBytesSent;
    

    Check if the data type is appropriate, and feel free to optimize this.