[experience stack] C # monitor the network speed and traffic of ipv4v6

Time:2021-5-12

1. Preface

Recently, the project needs to monitor the network speed and traffic. I failed to quickly find the use case of monitoring IPv6 traffic and network speed through Baidu and Google on the wall; Also after some of their own query and debugging, wasted a lot of time, now as experience to share out, I hope you correct.

2. C code

using System.Net.NetworkInformation;
using System.Timers;

namespace Monitor
{
    public class MonitorNetwork
    {      
        public string UpSpeed { get; set; }   
        public string DownSpeed { get; set; }
        public string AllTraffic { get; set; }            
        private string NetCardDescription { get; set; }    
        //The amount of data uploaded when a connection is established
        private long BaseTraffic { get; set; }    
        private long OldUp { get; set; }    
        private long OldDown { get; set; }
        private NetworkInterface networkInterface { get; set; }
        private Timer timer = new Timer() { Interval = 1000 };
    
        public void Close()
        {
            timer.Stop();   
        }
    
        public MonitorNetwork(string netCardDescription)
        {   
            timer.Elapsed += Timer_Elapsed;    
            NetCardDescription = netCardDescription;    
            timer.Interval = 1000;     
        }

        public bool Start()
        {
            networkInterface = null;    
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();    
            foreach (var var in nics)
            {
                if (var.Description.Contains(NetCardDescription))
                {
                    networkInterface = var;
                    break;
                }
            }    
            if (networkInterface == null)
            {
                return false;
            }
            else
            {    
                BaseTraffic = (networkInterface.GetIPStatistics().BytesSent +
                               networkInterface.GetIPStatistics().BytesReceived);    
                OldUp = networkInterface.GetIPStatistics().BytesSent;    
                OldDown = networkInterface.GetIPStatistics().BytesReceived;   
                timer.Start();    
                return true;
            }
    
        }

        private string[] units = new string[] {"KB/s","MB/s","GB/s" };

        private void CalcUpSpeed()
        {
            long nowValue = networkInterface.GetIPStatistics().BytesSent;    
            int num = 0;
            double value = (nowValue - OldUp) / 1024.0;
            while (value > 1023)
            {
                value = (value / 1024.0);
                num++;
            }   
            UpSpeed = value.ToString("0.0") + units[num];    
            OldUp = nowValue;    
        }
    
        private void CalcDownSpeed()
        {
            long nowValue = networkInterface.GetIPStatistics().BytesReceived;   
            int num = 0;
            double value = (nowValue - OldDown) / 1024.0;     
            while (value > 1023)
            {
                value = (value / 1024.0);
                num++;
            }    
            DownSpeed = value.ToString("0.0") + units[num];    
            OldDown = nowValue;    
        }
    
        private string[] unitAlls = new string[] { "KB", "MB", "GB" ,"TB"};
    
        private void CalcAllTraffic()
        {
            long nowValue = OldDown+OldUp;    
            int num = 0;
            double value = (nowValue- BaseTraffic) / 1024.0;
            while (value > 1023)
            {
                value = (value / 1024.0);
                num++;
            }   
            AllTraffic = value.ToString("0.0") + unitAlls[num];
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            CalcUpSpeed();
            CalcDownSpeed();
            CalcAllTraffic();
        }
    }
}

3. Nonsense

Although we can’t find the method directly and quickly, when we realize this demand, we have a spectrum in our heart. Windows system can monitor the network speed and traffic. There’s no reason why we can’t realize it. We just need a method to read this information. Finally, this requirement is realized by using the system. Net. Networkinformation assembly. However, this assembly does not only provide the method of network speed monitoring, but also provides the properties of the amount of data received and sent. You need to calculate the network speed by yourself, so the network speed is not particularly accurate.

In fact, I saw it from the beginning of this assembly. In the previous method, the bytesreceived attribute and bytessent attribute in the ipv4interfacestatistics class were used. However, there is no corresponding IPv6 class in this assembly, so I am in a trance.

IPv4InterfaceStatistics 类

Then, subconsciously, I thought that this assembly was old and didn’t support IPv6 statistics reading, and then all kinds of searches were fruitless. Later, I wanted to study it again and look around. Then I found a getipstatistics () method in the networkinterface class, which was described as “obtaining IP statistics of this networkinterface instance.”.

NetworkInterface 类

Then it’s a matter of course. According to the bytesreceived attribute and bytessent attribute in the ipinterfacestatistics instance returned by getipstatistics(), we can get the total amount of data received and sent, and then calculate the approximate network speed according to this information.

IPInterfaceStatistics 类

After testing, the total data volume of IPv4 and IPv6 can be read by using the ipinterfacestatistics instance, because the demand this time is to monitor the total volume. If you need to monitor IPv6 separately, you can subtract the IPv4 part from the total volume.

4. Postscript

  the teacher used to call me to study hard. I thought it was not enough to have Baidu. If I read again, I could have Baidu smart and know more about Baidu. Later, I gradually understood that Baidu knew more about Baidu, which was brought by the predecessors and encouraged each other.

reference material

System. Net. Networkinformation namespace

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]