archwhite
12/20/2016 - 1:05 PM

PerformanceCounter (Network Limiter)

PerformanceCounter (Network Limiter)

namespace TrafficLimiter
{
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using System.Linq;
    using System.Collections.Generic;
    using System.Runtime.Versioning;
    using System.Net.NetworkInformation;

    public class NetworkTraffic
    {
        private PerformanceCounter bytesSentPerformanceCounter;
        private PerformanceCounter bytesReceivedPerformanceCounter;

        public NetworkTraffic()
        {
            bytesSentPerformanceCounter = new PerformanceCounter();
            bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
            bytesSentPerformanceCounter.CounterName = "Bytes Sent";
            bytesSentPerformanceCounter.InstanceName = GetInstanceName();
            bytesSentPerformanceCounter.ReadOnly = false;
            bytesSentPerformanceCounter.InstanceLifetime = PerformanceCounterInstanceLifetime.Process;

            bytesReceivedPerformanceCounter = new PerformanceCounter();
            bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
            bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
            bytesReceivedPerformanceCounter.InstanceName = GetInstanceName();
            bytesReceivedPerformanceCounter.ReadOnly = false;
            bytesReceivedPerformanceCounter.InstanceLifetime = PerformanceCounterInstanceLifetime.Process;

            bool ok = PerformanceCounterCategory.CounterExists("Bytes Sent", ".NET CLR Networking");
            var x = new List<int>();
            var clist = PerformanceCounterCategory.GetCategories().Where(i => i.CategoryName.Contains("NET"));
            var cc = clist.Count();
        }


        public float GetBytesSent()
        {
            float bytesSent = bytesSentPerformanceCounter.RawValue;

            return bytesSent;
        }

        public float GetBytesReceived()
        {
            float bytesReceived = bytesReceivedPerformanceCounter.RawValue;

            return bytesReceived;
        }

        public void ResetCounterValues()
        {
            bytesSentPerformanceCounter.RawValue = 0;
            bytesReceivedPerformanceCounter.RawValue = 0;
        }

        private static string GetInstanceName()
        {
            return VersioningHelper.MakeVersionSafeName(
                AppDomain.CurrentDomain.FriendlyName,
                ResourceScope.Machine,
                ResourceScope.AppDomain);

        }

        public static bool PingHost(string nameOrAddress)
        {
            bool pingable = false;
            Ping pinger = new Ping();
            try
            {
                PingReply reply = pinger.Send(nameOrAddress);
                pingable = reply.Status == IPStatus.Success;
            }
            catch (PingException)
            {
                // Discard PingExceptions and return false;
                throw;
            }
            return pingable;
        }

        public static void Main()
        {
            NetworkTraffic networkTraffic = new NetworkTraffic();
            try
            {
                // send http get 5 times
#if true
                for (int i = 0; i < 5; i++)
                {
                    WebRequest webRequest = WebRequest.Create("http://www.google.com");
                    webRequest.Method = "GET";

                    using (WebResponse response = webRequest.GetResponse())
                    using (Stream responseStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                    }
                    Console.WriteLine("Bytes sent: {0}", networkTraffic.GetBytesSent());
                    Console.WriteLine("Bytes received: {0}", networkTraffic.GetBytesReceived());
                    Thread.Sleep(3000);
                }
#endif
                Console.WriteLine("Resetting counters ...");
                networkTraffic.ResetCounterValues();


#if true
                for (int i = 0; i < 5; i++)
                {
                    WebRequest webRequest = WebRequest.Create("http://www.google.com");
                    webRequest.Method = "GET";

                    using (WebResponse response = webRequest.GetResponse())
                    using (Stream responseStream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                    }
                    Console.WriteLine("Bytes sent: {0}", networkTraffic.GetBytesSent());
                    Console.WriteLine("Bytes received: {0}", networkTraffic.GetBytesReceived());
                    Thread.Sleep(3000);
                }
#endif

#if false
                Pinging is not calculated by windows perf.system
                // pinging forever
                while (true)
                {
                    PingHost("google.com");
                    Console.WriteLine("Bytes sent: {0}", networkTraffic.GetBytesSent());
                    Console.WriteLine("Bytes received: {0}", networkTraffic.GetBytesReceived());
                    Thread.Sleep(1000);
                }
#endif
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Console.ReadLine();
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <system.net>
    <settings>
      <performanceCounters enabled="true" />
    </settings>
  </system.net>
</configuration>