/// <summary> /// Evaluate the online network adapters to determine if at least one of them /// is capable of connecting to the Internet. /// </summary> /// <returns></returns> private static bool IsNetworkAvailable() { if (NetworkInterface.GetIsNetworkAvailable()) { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface face in interfaces) { if (face.OperationalStatus == OperationalStatus.Up) { if ((face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback) && (face.Description.ToLower().StartsWith("vmware") != true)) { IPv4InterfaceStatistics statistics = face.GetIPv4Statistics(); if ((statistics.BytesReceived > 0) && (statistics.BytesSent > 0)) { return(true); } } } } } return(false); }
private static byte[] NetStats() { if (!NetworkInterface.GetIsNetworkAvailable()) { return(new byte[0]); } NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); long[] state = new long[2]; foreach (NetworkInterface ni in interfaces) { if (ni.OperationalStatus == OperationalStatus.Up) { try { IPv4InterfaceStatistics stats = ni.GetIPv4Statistics(); if (stats.BytesSent + stats.BytesReceived > 0) { state[0] += (RotateLeft(stats.BytesSent, 24) ^ stats.UnicastPacketsReceived) + stats.UnicastPacketsSent; state[1] += (RotateRight(ni.GetIPv4Statistics().BytesReceived, 31) ^ stats.NonUnicastPacketsReceived) + stats.NonUnicastPacketsSent; } } catch { continue; } } } if (state[0] == 0 || state[1] == 0) { return(new byte[0]); } byte[] data = new byte[state.Length * 8]; Buffer.BlockCopy(state, 0, data, 0, data.Length); return(data); }
public void UpdateNetworkInterface() { NetworkInterface nic = nicArr[toolStripComboBox1.SelectedIndex]; IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); int bytesSent = (int)(interfaceStats.BytesSent - double.Parse(label4.Text)); int bytesRecv = (int)(interfaceStats.BytesReceived - double.Parse(label3.Text)); label3.Text = interfaceStats.BytesReceived.ToString(); label4.Text = interfaceStats.BytesSent.ToString(); string netRecvText = ""; string netSendText = ""; if (bytesRecv < 1024 * 1024) { netRecvText = ((double)bytesRecv / 1024).ToString("0.00") + "K/s"; } else if (bytesRecv >= 1024 * 1024) { netRecvText = ((double)bytesRecv / (1024 * 1024)).ToString("0.00") + "M/s"; } if (bytesSent < 1024 * 1024) { netSendText = ((double)bytesSent / 1024).ToString("0.00") + "K/s"; } else if (bytesSent >= 1024 * 1024) { netSendText = ((double)bytesSent / (1024 * 1024)).ToString("0.00") + "M/s"; } //更新控件 label1.Text = netSendText; label2.Text = netRecvText; }
/// <summary> /// Update GUI components for the network interfaces /// </summary> private void UpdateNetworkInterface() { //MessageBox.Show(cmbInterface.Items.Count.ToString()); if (cmbInterface.Items.Count >= 1) { // Grab NetworkInterface object that describes the current interface NetworkInterface nic = nicArr[cmbInterface.SelectedIndex]; // Grab the stats for that interface IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); long bytesSentSpeed = (long)(interfaceStats.BytesSent - double.Parse(lblBytesSent.Text)) / 1024; long bytesReceivedSpeed = (long)(interfaceStats.BytesReceived - double.Parse(lblBytesReceived.Text)) / 1024; // Update the labels lblSpeed.Text = nic.Speed.ToString(); lblInterfaceType.Text = nic.NetworkInterfaceType.ToString(); lblSpeed.Text = (nic.Speed).ToString("N0"); lblBytesReceived.Text = interfaceStats.BytesReceived.ToString("N0"); lblBytesSent.Text = interfaceStats.BytesSent.ToString("N0"); lblUpload.Text = bytesSentSpeed.ToString() + " KB/s"; lblDownload.Text = bytesReceivedSpeed.ToString() + " KB/s"; UnicastIPAddressInformationCollection ipInfo = nic.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation item in ipInfo) { if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { labelIPAddress.Text = item.Address.ToString(); //uniCastIPInfo = item; break; } } } }
// Информация о текущем соединении private void GetConnectionInfo() { NetworkInterface nic = null; try { // Выбираем активный адаптер nic = adaptersList[cbAdaptersList.SelectedIndex]; } catch { GetAdapters(); } // Статистика адаптера IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); // Подсчет текущей скорости int bytesSentSpeed = (int)(interfaceStats.BytesSent - lastSent) / 1024; int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - lastReceived) / 1024; // Update the labels //? labelSpeed.Text = (nic.Speed/1024).ToString()+" Kb/s"; //Тип интерфейса labelType.Text = nic.NetworkInterfaceType.ToString(); //Получено данных labelBytesReceived.Text = String.Format(new SizeFormatProvider(), "{0:fs}", interfaceStats.BytesReceived); lastReceived = interfaceStats.BytesReceived; //Отправлено данных labelBytesSent.Text = String.Format(new SizeFormatProvider(), "{0:fs}", interfaceStats.BytesSent); lastSent = interfaceStats.BytesSent; //Скорость приема labelUpload.Text = bytesSentSpeed.ToString() + " KB/s"; //Скорость отдачи labelDownload.Text = bytesReceivedSpeed.ToString() + " KB/s"; //Трафик за все время соединения labelTotal.Text = String.Format(new SizeFormatProvider(), "{0:fs}", interfaceStats.BytesReceived + interfaceStats.BytesSent); }
internal static bool IsNetworkAvailable() { try { // only recognizes changes related to Internet adapters if (NetworkInterface.GetIsNetworkAvailable()) { // however, this will include all adapters NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface face in interfaces) { // filter so we see only Internet adapters if (face.OperationalStatus == OperationalStatus.Up) { if ((face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)) { IPv4InterfaceStatistics statistics = face.GetIPv4Statistics(); //see if any bytes sent recieved if ((statistics.BytesReceived > 500) && (statistics.BytesSent > 500)) { return(true); } } } } } return(false); } catch (Exception e) { Error_Operation.Log_Error("IsNetworkAvailable()", e.Message.ToString(), e.StackTrace.ToString(), Error_Operation.LogSeverity.Verbose); return(false); } }
private static bool IsNetworkAvailable() { // only recognizes changes related to Internet adapters if (NetworkInterface.GetIsNetworkAvailable()) { // however, this will include all adapters NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface face in interfaces) { // filter so we see only Internet adapters if (face.OperationalStatus == OperationalStatus.Up) { if ((face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)) { IPv4InterfaceStatistics statistics = face.GetIPv4Statistics(); // all testing seems to prove that once an interface // comes online it has already accrued statistics for // both received and sent... if ((statistics.BytesReceived > 0) && (statistics.BytesSent > 0)) { return(true); } } } } } return(false); }
/// <summary> /// Ažurira podatke sa sučelja. /// </summary> private void UpdateStats() { while (true) { // Dohvati najnoviju statistiku IPv4InterfaceStatistics interfaceStats = this.interfaceInfo.GetIPv4Statistics(); // Ažuriraj vrijednosti, tj dodaj ih this.Bytes = new ChartValues <long> { interfaceStats.BytesReceived / 1000000, interfaceStats.BytesSent / 1000000 }; this.Packets = new ChartValues <long> { (interfaceStats.NonUnicastPacketsReceived + interfaceStats.UnicastPacketsReceived) / 1000, (interfaceStats.NonUnicastPacketsSent + interfaceStats.UnicastPacketsSent) / 1000, interfaceStats.IncomingPacketsDiscarded, interfaceStats.IncomingPacketsWithErrors, interfaceStats.IncomingUnknownProtocolPackets, interfaceStats.OutgoingPacketsDiscarded, interfaceStats.OutgoingPacketsWithErrors }; if (this.SeriesCollection == null) { return; } App.Current.Dispatcher.BeginInvoke((Action) delegate { this.SeriesCollection[0].Values = this.Bytes; this.SeriesCollection[1].Values = this.Packets; }); // Svaku minutu ažuriraj graf Task.Delay(60000).Wait(); } }
private void UpdateNetworkInterface() { try { Run += 1; IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); QueryPerformanceCounter(out Toc); ElapsedTime = (double)(Toc - Tic) / Freq; QueryPerformanceCounter(out Tic); double PreviousBytesSent = BytesSent; double PreviousBytesReceived = BytesReceived; BytesSent = interfaceStats.BytesSent; BytesReceived = interfaceStats.BytesReceived; if (Run > 0) { int bytesSentSpeed = (int)((double)(BytesSent - PreviousBytesSent) / ElapsedTime / 1024); int bytesReceivedSpeed = (int)((double)(BytesReceived - PreviousBytesReceived) / ElapsedTime / 1024); Console.WriteLine("Subida: " + (bytesSentSpeed).ToString() + " / " + "Bajada: " + (bytesReceivedSpeed).ToString() + " KBytes/s"); //ENVIAR PETICIÓN string URI = "http://localhost/controlarbandwidth/datos.php"; string myParameters = "id=" + Globals.ids + "&nombre=" + Globals.usuario + "&ip=" + Globals.iplocal + "&usosubida=" + bytesSentSpeed + "&usobajada=" + bytesReceivedSpeed; WebClient wc = new WebClient(); wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; wc.Headers[HttpRequestHeader.UserAgent] = "5FT7NY54O9T4FY5OFT9NY"; wc.Headers.Add("Content-Encoding", "gzip"); string html = wc.UploadString(URI, myParameters); // Codigo HTML resultante (debug) Console.WriteLine("Peticion realizada: " + myParameters); // } } catch (Exception excepcion) { Console.WriteLine("Excepcion producida en el bucle: " + excepcion); } }
private void GetIP() { string localIpAddress = string.Empty; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPv4InterfaceStatistics adapterStat = (nic).GetIPv4Statistics(); UnicastIPAddressInformationCollection uniCast = (nic).GetIPProperties().UnicastAddresses; if (uniCast != null) { foreach (UnicastIPAddressInformation uni in uniCast) { if (adapterStat.UnicastPacketsReceived > 0 && adapterStat.UnicastPacketsSent > 0 && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) { if (uni.Address.AddressFamily == AddressFamily.InterNetwork) { localIpAddress = nic.GetIPProperties().UnicastAddresses[1].Address.ToString(); break; } } } } } textField.text += localIpAddress + "\n"; }
/// <summary> /// /// </summary> /// <returns>ip, speed or null, null</returns> private static string[] IsNetworkAvailableWithValues() { string[] returnValues = new string[2]; // only recognizes changes related to Internet adapters if (NetworkInterface.GetIsNetworkAvailable()) { // however, this will include all adapters NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface face in interfaces) { // filter so we see only Internet adapters if (face.OperationalStatus == OperationalStatus.Up) { if ((face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)) { IPv4InterfaceStatistics statistics = face.GetIPv4Statistics(); // all testing seems to prove that once an interface comes online // it has already accrued statistics for both received and sent... if ((statistics.BytesReceived > 0) && (statistics.BytesSent > 0)) { returnValues[0] = face.GetIPProperties().UnicastAddresses[0].Address.ToString(); returnValues[1] = face.Speed.ToString(); return(returnValues); } } } } } return(returnValues); }
private void DumpNetworkStats() { Console.WriteLine(); Console.WriteLine("Domain name is [{0}]", NetworkStatus.GetBestDomainName()); bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); Console.WriteLine(String.Format("isAvailable = [{0}]", isAvailable ? "Yes" : "No")); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface face in interfaces) { Console.WriteLine(String.Format( "Interface [{0}] ({1}), type=[{2}]", face.Name, face.Description, face.NetworkInterfaceType.ToString())); IPv4InterfaceStatistics stats = face.GetIPv4Statistics(); Console.WriteLine(String.Format( " Status......: [{0}] Rcv/Snd=[{1}/{2}]", face.OperationalStatus.ToString(), stats.BytesReceived, stats.BytesSent)); } }
private void Btn_Settings_Click(object sender, RoutedEventArgs e) { if (NetworkInterface.GetIsNetworkAvailable()) { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface Interface in interfaces) { if (Interface.Description == VPNManagement.VPNAdapterName && Interface.OperationalStatus == OperationalStatus.Up) { if ((Interface.NetworkInterfaceType == NetworkInterfaceType.Ppp) && (Interface.NetworkInterfaceType != NetworkInterfaceType.Loopback)) { var test = Interface; IPv4InterfaceStatistics statistics = Interface.GetIPv4Statistics(); MessageBox.Show(Interface.Name + " " + Interface.NetworkInterfaceType.ToString() + " " + Interface.Description); } else { MessageBox.Show("VPN Connection is lost!"); } } } } }
/// <summary> /// 获取系统网络流量情况: /// 上传、下载 /// 此功能与网卡有关,目前暂不确定是否可行 /// </summary> public SystemInternet GetSystemInternet() { //网卡不确定有几个,默认[0](本地连接) //可在:控制面板-网络和 Internet-网络连接 中查看网卡 NetworkInterface nic = _interfaceCard[0]; IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(_uploadInternet)) / 1024; int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(_downloadInternet)) / 1024; _uploadInternet = interfaceStats.BytesSent.ToString(); _downloadInternet = interfaceStats.BytesReceived.ToString(); return(new SystemInternet { InternetName = nic.Name, InternetType = nic.NetworkInterfaceType.ToString(), ALLDownloadByte = interfaceStats.BytesReceived.ToString(), AllUpLoadByte = interfaceStats.BytesSent.ToString(), UploadByte = bytesSentSpeed.ToString(), DownloadByte = bytesReceivedSpeed.ToString(), DateTimeNow = DateTime.Now }); }
public void RegisterServerStats() { // lastperformanceCounterSampleTime = Util.EnvironmentTickCount(); PerformanceCounter tempPC; Stat tempStat; string tempName; try { tempName = "CPUPercent"; tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total"); processorPercentPerfCounter = new PerfCounterControl(tempPC); // A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy. tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor, StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); }, StatVerbosity.Info); StatsManager.RegisterStat(tempStat); RegisteredStats.Add(tempName, tempStat); MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); }); MakeStat("UserProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); }); MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); }); MakeStat("Threads", null, "threads", ContainerProcessor, (s) => { s.Value = Process.GetCurrentProcess().Threads.Count; }); } catch (Exception e) { m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e); } MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool, s => { int workerThreads, iocpThreads; ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads); s.Value = workerThreads; }); MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool, s => { int workerThreads, iocpThreads; ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads); s.Value = iocpThreads; }); if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null) { MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads); MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads); MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems); MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads); MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads); MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks); } MakeStat( "HTTPRequestsMade", "Number of outbound HTTP requests made", "requests", ContainerNetwork, s => s.Value = WebUtil.RequestNumber, MeasuresOfInterest.AverageChangeOverTime); try { List <string> okInterfaceTypes = new List <string>(NetworkInterfaceTypes.Split(',')); IEnumerable <NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } string nicInterfaceType = nic.NetworkInterfaceType.ToString(); if (!okInterfaceTypes.Contains(nicInterfaceType)) { m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.", LogHeader, nic.Name, nicInterfaceType); m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}", LogHeader, NetworkInterfaceTypes); continue; } if (nic.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics(); if (nicStats != null) { MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesReceived); }, 1024.0); }); MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesSent); }, 1024.0); }); MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesSent + ns.BytesReceived); }, 1024.0); }); } } // TODO: add IPv6 (it may actually happen someday) } } catch (Exception e) { m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e); } MakeStat("ProcessMemory", null, "MB", ContainerMemory, (s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); }); MakeStat("HeapMemory", null, "MB", ContainerMemory, (s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); }); MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory, (s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); }); MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory, (s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); }); }
/// <summary> /// Takes a network load snapshot (CurrentNetworkLoad) every NetworkLoadUpdateWindowMS /// </summary> private static void NetworkLoadWorker() { NetworkLoadThreadWait = new ManualResetEvent(false); //Get all interfaces NetworkInterface[] interfacesToUse = NetworkInterface.GetAllNetworkInterfaces(); long[] startSent, startReceived, endSent, endReceived; while (!NetworkComms.commsShutdown) { try { //we need to look at the load across all adaptors, by default we will probably choose the adaptor with the highest usage DateTime startTime = DateTime.Now; IPv4InterfaceStatistics[] stats = new IPv4InterfaceStatistics[interfacesToUse.Length]; startSent = new long[interfacesToUse.Length]; startReceived = new long[interfacesToUse.Length]; for (int i = 0; i < interfacesToUse.Length; ++i) { stats[i] = interfacesToUse[i].GetIPv4Statistics(); startSent[i] = stats[i].BytesSent; startReceived[i] = stats[i].BytesReceived; } if (NetworkComms.commsShutdown) { return; } //Thread.Sleep(NetworkLoadUpdateWindowMS); #if NET2 NetworkLoadThreadWait.WaitOne(NetworkLoadUpdateWindowMS, false); #else NetworkLoadThreadWait.WaitOne(NetworkLoadUpdateWindowMS); #endif if (NetworkComms.commsShutdown) { return; } stats = new IPv4InterfaceStatistics[interfacesToUse.Length]; endSent = new long[interfacesToUse.Length]; endReceived = new long[interfacesToUse.Length]; for (int i = 0; i < interfacesToUse.Length; ++i) { stats[i] = interfacesToUse[i].GetIPv4Statistics(); endSent[i] = stats[i].BytesSent; endReceived[i] = stats[i].BytesReceived; } DateTime endTime = DateTime.Now; List <double> outUsage = new List <double>(); List <double> inUsage = new List <double>(); for (int i = 0; i < startSent.Length; i++) { outUsage.Add((double)(endSent[i] - startSent[i]) / ((double)(InterfaceLinkSpeed * (endTime - startTime).TotalMilliseconds) / 8000)); inUsage.Add((double)(endReceived[i] - startReceived[i]) / ((double)(InterfaceLinkSpeed * (endTime - startTime).TotalMilliseconds) / 8000)); } //double loadValue = Math.Max(outUsage.Max(), inUsage.Max()); double inMax = double.MinValue, outMax = double.MinValue; for (int i = 0; i < startSent.Length; ++i) { if (inUsage[i] > inMax) { inMax = inUsage[i]; } if (outUsage[i] > outMax) { outMax = outUsage[i]; } } //If either of the usage levels have gone above 2 it suggests we are most likely on a faster connection that we think //As such we will bump the interface link speed up to 1Gbps so that future load calculations more accurately reflect the //actual load. if (inMax > 2 || outMax > 2) { InterfaceLinkSpeed = 950000000; } //Limit to one CurrentNetworkLoadIncoming = (inMax > 1 ? 1 : inMax); CurrentNetworkLoadOutgoing = (outMax > 1 ? 1 : outMax); currentNetworkLoadValuesIncoming.AddValue(CurrentNetworkLoadIncoming); currentNetworkLoadValuesOutgoing.AddValue(CurrentNetworkLoadOutgoing); //We can only have up to 255 seconds worth of data in the average list int maxListSize = (int)(255000.0 / NetworkLoadUpdateWindowMS); currentNetworkLoadValuesIncoming.TrimList(maxListSize); currentNetworkLoadValuesOutgoing.TrimList(maxListSize); } catch (Exception ex) { //There is no need to log if the exception is due to a change in interfaces if (ex.GetType() != typeof(NetworkInformationException)) { LogTools.LogException(ex, "NetworkLoadWorker"); } //It may be the interfaces available to the OS have changed so we will reset them here interfacesToUse = NetworkInterface.GetAllNetworkInterfaces(); //If an error has happened we don't want to thrash the problem, we wait for 5 seconds and hope whatever was wrong goes away Thread.Sleep(5000); } } }
public static long[] GetTotalNetworkBytes() { IPv4InterfaceStatistics netAdapterStats = NetworkInterface.GetAllNetworkInterfaces().Where(x => x.OperationalStatus == OperationalStatus.Up).Select(x => x.GetIPv4Statistics()).ToArray()[0]; return(new long[] { netAdapterStats.BytesReceived, netAdapterStats.BytesSent }); }
//protected void btn_Speed_Click(object sender, EventArgs e) //{ //} private void InternetSpeed() { try { //double[] speeds = new double[5]; //for (int i = 0; i < 5; i++) //{ // int jQueryFileSize = 261; //Size of File in KB. // WebClient client = new WebClient(); // DateTime startTime = DateTime.Now; // client.DownloadFile("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js", Server.MapPath("~/jQuery.js")); // DateTime endTime = DateTime.Now; // speeds[i] = Math.Round((jQueryFileSize / (endTime - startTime).TotalSeconds)); //} //lblDownloadSpeed.Text = string.Format("Download Speed: {0}KB/s", speeds.Average()); // System.Net.NetworkInformation.NetworkInterface[] nics = null; nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); foreach (System.Net.NetworkInformation.NetworkInterface net in NetworkInterface.GetAllNetworkInterfaces()) { if (net.Name.Contains("Wireless") || net.Name.Contains("WiFi") || net.Name.Contains("802.11") || net.Name.Contains("Wi-Fi")) { speed = net.Speed; adapter = net.Name; networkInterface = net; break; } } string temp; if (speed == 0) { temp = "There is currently no Wi-Fi connection"; foreach (NetworkInterface currentNetworkInterface in NetworkInterface.GetAllNetworkInterfaces()) { if (currentNetworkInterface.Name.ToLower() == "local area connection") { networkInterface = currentNetworkInterface; break; } else { speed = currentNetworkInterface.Speed; networkInterface = currentNetworkInterface; break; } } IPv4InterfaceStatistics interfaceStatistic = networkInterface.GetIPv4Statistics(); int bytesSentSpeed = (int)(interfaceStatistic.BytesSent - lngBytesSend) / 1; int bytesReceivedSpeed = (int)(interfaceStatistic.BytesReceived - lngBtyesReceived) / 1; adapter = networkInterface.Name; // lblSpeed.Text = (networkInterface.Speed / 1000000).ToString() + " Mbps on " + adapter; // lblPacketReceived.Text = ((interfaceStatistic.UnicastPacketsReceived) / 1).ToString() + " Mbps"; // lblPacketSend.Text = ((interfaceStatistic.UnicastPacketsSent) / 1).ToString() + " Mbps"; // lblUpload.Text = (bytesSentSpeed).ToString() + " Bytes / s"; // lblDownLoad.Text = (bytesReceivedSpeed).ToString() + " Bytes / s "; lngBytesSend = interfaceStatistic.BytesSent; lngBtyesReceived = interfaceStatistic.BytesReceived; } else { foreach (System.Net.NetworkInformation.NetworkInterface net in NetworkInterface.GetAllNetworkInterfaces()) { if (net.Name.Contains("Wireless") || net.Name.Contains("WiFi") || net.Name.Contains("802.11") || net.Name.Contains("Wi-Fi")) { temp = "Current Wi-Fi Speed: " + (speed / 1000000) + "Mbps on " + adapter; // lblSpeed.Text = temp; IPv4InterfaceStatistics interfaceStatistic = networkInterface.GetIPv4Statistics(); int bytesSentSpeed = (int)(interfaceStatistic.BytesSent - lngBytesSend) / 1; int bytesReceivedSpeed = (int)(interfaceStatistic.BytesReceived - lngBtyesReceived) / 1; // lblSpeed.Text = (networkInterface.Speed / 1000000).ToString() + " Mbps"; // lblPacketReceived.Text = ((interfaceStatistic.UnicastPacketsReceived) / 1).ToString() + " Mbps"; // lblPacketSend.Text = ((interfaceStatistic.UnicastPacketsSent) / 1).ToString() + " Mbps"; // lblUpload.Text = (bytesSentSpeed).ToString() + " Bytes / s"; // lblDownLoad.Text = (bytesReceivedSpeed).ToString() + " Bytes / s "; lngBytesSend = interfaceStatistic.BytesSent; lngBtyesReceived = interfaceStatistic.BytesReceived; } } } } catch (Exception ex) { } // }
public void RegisterServerStats() { lastperformanceCounterSampleTime = Util.EnvironmentTickCount(); PerformanceCounter tempPC; Stat tempStat; string tempName; try { tempName = "CPUPercent"; tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total"); processorPercentPerfCounter = new PerfCounterControl(tempPC); // A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy. tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor, StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter, Util.IsWindows() ? 1 : -1); }, StatVerbosity.Info); StatsManager.RegisterStat(tempStat); RegisteredStats.Add(tempName, tempStat); MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; }); MakeStat("UserProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds; }); MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor, (s) => { s.Value = Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds; }); MakeStat("Threads", null, "threads", ContainerProcessor, (s) => { s.Value = Process.GetCurrentProcess().Threads.Count; }); } catch (Exception e) { m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e); } try { List <string> okInterfaceTypes = new List <string>(NetworkInterfaceTypes.Split(',')); IEnumerable <NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } string nicInterfaceType = nic.NetworkInterfaceType.ToString(); if (!okInterfaceTypes.Contains(nicInterfaceType)) { m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.", LogHeader, nic.Name, nicInterfaceType); m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}", LogHeader, NetworkInterfaceTypes); continue; } if (nic.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics(); if (nicStats != null) { MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesReceived); }, 1024.0); }); MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesSent); }, 1024.0); }); MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork, (s) => { LookupNic(s, (ns) => { return(ns.BytesSent + ns.BytesReceived); }, 1024.0); }); } } // TODO: add IPv6 (it may actually happen someday) } } catch (Exception e) { m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e); } MakeStat("ProcessMemory", null, "MB", ContainerMemory, (s) => { s.Value = Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d; }); MakeStat("ObjectMemory", null, "MB", ContainerMemory, (s) => { s.Value = GC.GetTotalMemory(false) / 1024d / 1024d; }); MakeStat("LastMemoryChurn", null, "MB/sec", ContainerMemory, (s) => { s.Value = Math.Round(MemoryWatchdog.LastMemoryChurn * 1000d / 1024d / 1024d, 3); }); MakeStat("AverageMemoryChurn", null, "MB/sec", ContainerMemory, (s) => { s.Value = Math.Round(MemoryWatchdog.AverageMemoryChurn * 1000d / 1024d / 1024d, 3); }); }
static void Main(string[] args) { string macType = string.Empty; long maxSpeed = 1; for (; ;) { //look at each adapter found and list it. foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { var temptype = nic.NetworkInterfaceType.ToString(); IPv4InterfaceStatistics stats = nic.GetIPv4Statistics(); //ethernet adpter that is connected (diffrent types) if (nic.Speed > maxSpeed && temptype == "Ethernet") { //Deal with Bluetooth Nic that shows as wired if (nic.Name == "Bluetooth Network Connection") { //do noting } else { Console.WriteLine("Wired Network connection Found."); Console.WriteLine("Name:" + nic.Name); Console.WriteLine("Speed: " + nic.Speed); Console.WriteLine("Output queue length: " + stats.OutputQueueLength); Console.WriteLine("Bytes recieved: " + stats.BytesReceived); Console.WriteLine("Bytes sent: " + stats.BytesSent); Console.WriteLine("incoming errors: " + stats.IncomingPacketsWithErrors); Console.WriteLine("Outgoing errors: " + stats.OutgoingPacketsWithErrors); Console.WriteLine("incoming packets discarded: " + stats.IncomingPacketsDiscarded); Console.WriteLine("Outgoing packets discarded " + stats.OutgoingPacketsDiscarded); Console.WriteLine("NonUnicast packets sent: " + stats.NonUnicastPacketsSent); Console.WriteLine("NonUnicast packets Recieved: " + stats.NonUnicastPacketsReceived); Console.WriteLine("Unicast packets sent: " + stats.UnicastPacketsSent); Console.WriteLine("Unicast packets Recieved: " + stats.UnicastPacketsReceived); Console.WriteLine(""); using (StreamWriter w = File.AppendText(@"C:\temp\NWQ_Check.log")) { Log("-----------------------------------------------------------------------------------------------------------------", w); Log("Wired Network connection Found.", w); Log("Name:" + nic.Name, w); Log("Speed: " + nic.Speed, w); Log("Output queue length: " + stats.OutputQueueLength, w); Log("Bytes recieved: " + stats.BytesReceived, w); Log("Bytes sent: " + stats.BytesSent, w); Log("incoming errors: " + stats.IncomingPacketsWithErrors, w); Log("Outgoing errors: " + stats.OutgoingPacketsWithErrors, w); Log("incoming packets discarded: " + stats.IncomingPacketsDiscarded, w); Log("Outgoing packets discarded " + stats.OutgoingPacketsDiscarded, w); Log("NonUnicast packets sent: " + stats.NonUnicastPacketsSent, w); Log("NonUnicast packets Recieved: " + stats.NonUnicastPacketsReceived, w); Log("Unicast packets sent: " + stats.UnicastPacketsSent, w); Log("Unicast packets Recieved: " + stats.UnicastPacketsReceived, w); Log("-----------------------------------------------------------------------------------------------------------------", w); } } } if (nic.Speed > maxSpeed && temptype == "GigabitEthernet") { Console.WriteLine("Wired GB connection Found."); Console.WriteLine("Name:" + nic.Name); Console.WriteLine("Speed: " + nic.Speed); Console.WriteLine("Output queue length: " + stats.OutputQueueLength); Console.WriteLine("Bytes recieved: " + stats.BytesReceived); Console.WriteLine("Bytes sent: " + stats.BytesSent); Console.WriteLine("incoming errors: " + stats.IncomingPacketsWithErrors); Console.WriteLine("Outgoing errors: " + stats.OutgoingPacketsWithErrors); Console.WriteLine("incoming packets discarded: " + stats.IncomingPacketsDiscarded); Console.WriteLine("Outgoing packets discarded " + stats.OutgoingPacketsDiscarded); Console.WriteLine("NonUnicast packets sent: " + stats.NonUnicastPacketsSent); Console.WriteLine("NonUnicast packets Recieved: " + stats.NonUnicastPacketsReceived); Console.WriteLine("Unicast packets sent: " + stats.UnicastPacketsSent); Console.WriteLine("Unicast packets Recieved: " + stats.UnicastPacketsReceived); Console.WriteLine(""); using (StreamWriter w = File.AppendText(@"C:\temp\NWQ_Check.log")) { Log("-----------------------------------------------------------------------------------------------------------------", w); Log("Wired GB Network connection Found.", w); Log("Name:" + nic.Name, w); Log("Speed: " + nic.Speed, w); Log("Output queue length: " + stats.OutputQueueLength, w); Log("Bytes recieved: " + stats.BytesReceived, w); Log("Bytes sent: " + stats.BytesSent, w); Log("incoming errors: " + stats.IncomingPacketsWithErrors, w); Log("Outgoing errors: " + stats.OutgoingPacketsWithErrors, w); Log("incoming packets discarded: " + stats.IncomingPacketsDiscarded, w); Log("Outgoing packets discarded " + stats.OutgoingPacketsDiscarded, w); Log("NonUnicast packets sent: " + stats.NonUnicastPacketsSent, w); Log("NonUnicast packets Recieved: " + stats.NonUnicastPacketsReceived, w); Log("Unicast packets sent: " + stats.UnicastPacketsSent, w); Log("Unicast packets Recieved: " + stats.UnicastPacketsReceived, w); Log("-----------------------------------------------------------------------------------------------------------------", w); } } } Thread.Sleep(10000); } //Console.ReadKey(); }
private void UpdateNetworkInterface() { if (ComboBox_Network_interface.Items.Count >= 1) // if the number of items are less greater than or equal to one { // Grab NetworkInterface object that describes the current interface NetworkInterface nic = nicArr[ComboBox_Network_interface.SelectedIndex]; IPInterfaceProperties properties = nic.GetIPProperties(); Object test = nic.Speed; // Grab the stats for that interface IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); //takes the bytes sent from the interface and put it in the text for the bytes sent amount text of the text block. String BytesSentAmountCastContent2; BytesSentAmountCastContent2 = (String)BytesSentAmountLabel.Content; long bytesSentSpeed = (long)(interfaceStats.BytesSent - double.Parse(BytesSentAmountCastContent2)) / 1000; //converts the bytes to a KiloBytes(kB). long SentSpeedToMegaBytes = bytesSentSpeed / 1000; // converts the sentspeed from kilobytes(KB) to MegaBytes(MB) // String BytesSentSpeedToDouble = Convert.ToDouble(by) //long whatever = ByteSentSpeedToObject - (bytesSentSpeed / 1024); BytesSentAmountLabel.Content = interfaceStats.BytesSent.ToString("N0"); // sets the label text to be equal to the bytes sent speed. String BytesReceivedAmountCast; BytesReceivedAmountCast = (String)BytesReceivedAmountLabel.Content; //takes the bytes received from the interface and put it in the text for the bytes received amount text of the text block. long bytesReceivedSpeed = (long)(interfaceStats.BytesReceived - double.Parse(BytesReceivedAmountCast)) / 1000; //String ByteRecievedToString = bytesReceivedSpeed.ToString("N0") + " KB/s"; // converts it to a string with commas separating it. BytesReceivedAmountLabel.Content = interfaceStats.BytesReceived.ToString("N0"); // Update the labels long SpeedAmountBytes = (long)(nic.Speed / 8000); String SpeedAmountBytesToString = SpeedAmountBytes.ToString("N0") + " KB/s"; SpeedAmountLabel.Content = SpeedAmountBytesToString; //Bytes_Received_amount_Textblock.Text = interfaceStats.BytesReceived.ToString("N0"); // Bytes_Sent_amount.Text = interfaceStats.BytesSent.ToString("N0"); UploadAmountLabel.Content = bytesSentSpeed.ToString() + " KB/s"; DownloadAmountLabel.Content = bytesReceivedSpeed.ToString() + " KB/s"; //gets the current date and time. DateTime now = DateTime.Now; String BytseSentSpeedString = bytesSentSpeed.ToString(); String DownloadString = bytesReceivedSpeed.ToString(); String DateTimeString = now.ToString("hh:mm"); UpdateList(DateTimeString, BytseSentSpeedString, DownloadString); //GenerateExcelFileandUpdate(BytseSentSpeedString, DownloadString); //add the current upload speed to the tuple. //var DataStuff = new List<Tuple<String, String, Object>> Tuple <String, String, Object> DataTuple = new Tuple <String, String, Object>(now.ToString(), "Upload", bytesSentSpeed.ToString()); //DataTuple. // get the IP address of the current selected network interface. UnicastIPAddressInformationCollection ipInfo = nic.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation item in ipInfo) { //if the IP address is in the system range of Ip addresses if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { IP_Address_Of_Computer.Content = item.Address.ToString(); // add the IP address to the text of IP address info text block. break; } } } }
private void WriteTotalNetworkBytes() { int intIndicatorPacketSize = AppRegistry.GetIntValue( Application.CompanyName, Application.ProductName, "NetworkNotificatioIndicatorPacketSize", DEFAULT_INDICATOR_PACKET_SIZE); //Aggregate values long lBytesReceived = 0; long lBytesSend = 0; foreach (NetworkInterface adapter in NetworkInterfaces) { IPInterfaceProperties properties = adapter.GetIPProperties(); if (!adapter.Supports(NetworkInterfaceComponent.IPv4)) { continue; } IPv4InterfaceStatistics ipv4stats = adapter.GetIPv4Statistics(); lBytesReceived += ipv4stats.BytesReceived; lBytesSend += ipv4stats.BytesSent; } //Check if this is the first time if (m_lBytesReceived == long.MinValue) { m_lBytesReceived = lBytesReceived; } if (m_lBytesSent == long.MinValue) { m_lBytesSent = lBytesSend; } //Update Icons if (m_bNetworkAvailable) { if (lBytesSend - m_lBytesSent > intIndicatorPacketSize && lBytesReceived - m_lBytesReceived > intIndicatorPacketSize) { //Update values for next time m_lBytesReceived = lBytesReceived; m_lBytesSent = lBytesSend; OnTrafficSentReceived(EventArgs.Empty); } else if (lBytesSend - m_lBytesSent > intIndicatorPacketSize) { //Update values for next time m_lBytesSent = lBytesSend; OnTrafficSent(EventArgs.Empty); } else if (lBytesReceived - m_lBytesReceived > intIndicatorPacketSize) { //Update values for next time m_lBytesReceived = lBytesReceived; OnTrafficReceived(EventArgs.Empty); } else { //m_intIconIndex = 0; OnNetworkAvailable(new NetworkStatusChangedEventArgs(false)); } } else { OnNetworkUnavailable(new NetworkStatusChangedEventArgs(false)); } }
static void Main(string[] args) { Int32 cycleCount = 1; NetworkInterface netif = null; Console.WriteLine(RationalCityPostExampleVersion.ToString()); if (args.Count() == 0) { foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces()) { PhysicalAddress ph = n.GetPhysicalAddress(); IPInterfaceProperties ipp = n.GetIPProperties(); UnicastIPAddressInformationCollection ua = ipp.UnicastAddresses; Console.WriteLine(ph.ToString().ToUpper()); foreach (UnicastIPAddressInformation u in ua) { Console.WriteLine(" Unicast Address ......................... : {0}", u.Address); } } } else { foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces()) { PhysicalAddress ph = n.GetPhysicalAddress(); if (ph.ToString().ToUpper() == args[0].ToUpper()) { netif = n; break; } } if (args.Count() > 1) { domain = args[1]; } if (args.Count() > 2) { sleep = Int32.Parse(args[2]); } if (args.Count() > 3) { templateFileName = args[3]; } } StreamReader r = System.IO.File.OpenText(templateFileName); String xmlTemplate = r.ReadToEnd(); for (; ;) { if (netif != null) { IPv4InterfaceStatistics stat = netif.GetIPv4Statistics(); DateTime now = DateTime.Now; String result = xmlTemplate; Int64[] values = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; String[] units = { "kB", "kB", "pieces", "pieces", "pieces", "pieces", "pieces", "pieces", "pieces", "pieces" }; values[0] = stat.BytesSent / 1000; values[1] = stat.BytesReceived / 1000; values[2] = stat.IncomingPacketsDiscarded; values[3] = stat.IncomingPacketsWithErrors; values[4] = stat.IncomingUnknownProtocolPackets; values[5] = stat.NonUnicastPacketsReceived; values[6] = stat.NonUnicastPacketsSent; values[7] = stat.UnicastPacketsReceived; values[8] = stat.UnicastPacketsSent; values[9] = stat.OutputQueueLength; for (Int32 j = 1; j <= 10; j++) { result = result.Replace("@@VALUE_Value_" + j.ToString() + "@@", values[j - 1].ToString()); result = result.Replace("@@STRING_VALUE_Value_" + j.ToString() + "@@", values[j - 1].ToString()); result = result.Replace("@@STATUS_Value_" + j.ToString() + "@@", "0"); result = result.Replace("@@UNITS_Value_" + j.ToString() + "@@", units[j - 1]); result = result.Replace("@@YEAR_Value_" + j.ToString() + "@@", now.Year.ToString()); result = result.Replace("@@MONTH_Value_" + j.ToString() + "@@", now.Month.ToString()); result = result.Replace("@@DAY_OF_MONTH_Value_" + j.ToString() + "@@", now.Day.ToString()); result = result.Replace("@@DAY_OF_WEEK_Value_" + j.ToString() + "@@", now.DayOfWeek.ToString()); result = result.Replace("@@HOUR_Value_" + j.ToString() + "@@", now.Hour.ToString()); result = result.Replace("@@MINUTE_Value_" + j.ToString() + "@@", now.Minute.ToString()); result = result.Replace("@@SECOND_Value_" + j.ToString() + "@@", now.Second.ToString()); // according to IEC62056-62 p.13 result = result.Replace("@@HUNDREDTHS_OF_SECOND_Value_" + j.ToString() + "@@", (now.Millisecond / 10).ToString()); } System.IO.File.WriteAllText(xmlFileName, result); try { RationalCityPostExample.SendRequest(); } catch (Exception e) { Console.WriteLine("Exception: " + (String)(e.InnerException != null ? e.InnerException.Message : e.Message)); } Console.WriteLine("Cycle " + cycleCount.ToString() + " time: " + now.ToString()); cycleCount++; } Thread.Sleep(sleep); } }
private static void run() { while (true) { try { lock (lockObj) { NetworkInterface[] nifs = NetworkInterface.GetAllNetworkInterfaces(); if (nifs != null && nifs.Length > 0) { long tmpRecvByte = 0; long tmpSendByte = 0; foreach (var nif in nifs) { if (nif.OperationalStatus == OperationalStatus.Up && (nif.NetworkInterfaceType == NetworkInterfaceType.Ethernet || nif.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)) { IPv4InterfaceStatistics statis = nif.GetIPv4Statistics(); if (statis.BytesReceived > 0 || statis.BytesSent > 0) { tmpRecvByte += statis.BytesReceived; tmpSendByte += statis.BytesSent; if (string.IsNullOrEmpty(NetWorkStat.Mac) || NetWorkStat.Mac == "00-00-00-00-00-00") { NetWorkStat.Mac = nif.GetPhysicalAddress().ToString(); NetWorkStat.Mac = InsertFormat(NetWorkStat.Mac, 2, "-").TrimEnd('-').ToUpper(); } } } } if (_recvPer == 0 || _sendPer == 0) { NetWorkStat.CurrentRecvBytes = 0; NetWorkStat.CurrentSendBytes = 0; NetWorkStat.TotalRecvBytes = 0; NetWorkStat.TotalSendBytes = 0; _recvPer = (ulong)tmpRecvByte; _sendPer = (ulong)tmpSendByte; } else { NetWorkStat.UpdateTime = DateTime.Now; NetWorkStat.CurrentRecvBytes = (ulong)tmpRecvByte - _recvPer; NetWorkStat.CurrentSendBytes = (ulong)tmpSendByte - _sendPer; NetWorkStat.TotalRecvBytes = (ulong)tmpRecvByte; NetWorkStat.TotalSendBytes = (ulong)tmpSendByte; _recvPer = (ulong)tmpRecvByte; _sendPer = (ulong)tmpSendByte; } } } Thread.Sleep(1000); } catch { // } } }
//mobile stuk public void mobile_checkBox_Checked(object sender, RoutedEventArgs e) { mobile_password_label.Content = "Checking mobile networks...."; //create mobile profile if not exist CreateMobileProfile(); //netsh mbn show profile MBNConnect.MBNConnect connectInfo = new MBNConnect.MBNConnect(); NetworkInterface[] networkIntrInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in networkIntrInterfaces) { //select only mobile apn if (networkInterface.Name.Contains("Mobile Broadband adapter Mobiel")) { IPv4InterfaceStatistics interfaceStats = networkInterface.GetIPv4Statistics(); int bytesSentSpeed = (int)(interfaceStats.BytesSent); string id = (string)networkInterface.Id; string name = (string)networkInterface.Name; string description = (string)networkInterface.Description; PhysicalAddress physical_address = networkInterface.GetPhysicalAddress(); //create the view var gridview = new GridView(); this.mobile_listView.View = gridview; gridview.Columns.Add(new GridViewColumn { Header = "Name", DisplayMemberBinding = new System.Windows.Data.Binding("Name") }); gridview.Columns.Add(new GridViewColumn { Header = "Id", DisplayMemberBinding = new System.Windows.Data.Binding("Id") }); gridview.Columns.Add(new GridViewColumn { Header = "Adress", DisplayMemberBinding = new System.Windows.Data.Binding("Adress") }); gridview.Columns.Add(new GridViewColumn { Header = "Netwerk", DisplayMemberBinding = new System.Windows.Data.Binding("Netwerk") }); gridview.Columns.Add(new GridViewColumn { Header = "MaxBandWidth", DisplayMemberBinding = new System.Windows.Data.Binding("MaxBandWidth") }); gridview.Columns.Add(new GridViewColumn { Header = "BytesSentSpeed", DisplayMemberBinding = new System.Windows.Data.Binding("BytesSentSpeed") }); int maxBandWidth = connectInfo.GetMaxBandwidth(); mobile_listView.Items.Add(new MBNConnect.MBNConnect { Name = name, Id = id, Adress = physical_address, Netwerk = networkInterface.Description, MaxBandWidth = maxBandWidth, BytesSentSpeed = bytesSentSpeed }); } } }
public void ShowInterfaceSpeedAndQueue() { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); //Console.WriteLine("Interface information for {0}.{1} ", computerProperties.HostName, computerProperties.DomainName); SetTextLine(String.Format("Interface information for {0}.{1} ", computerProperties.HostName, computerProperties.DomainName)); if (adapters == null || adapters.Length < 1) { //Console.WriteLine(" No network interfaces found."); SetTextLine(" No network interfaces found."); return; } //Console.WriteLine(" Number of interfaces .................... : {0}", adapters.Length); SetTextLine(String.Format(" Number of interfaces .................... : {0}", adapters.Length)); foreach (NetworkInterface adapter in adapters) { System.Windows.Forms.Application.DoEvents(); IPInterfaceProperties properties = adapter.GetIPProperties(); //Console.WriteLine(String.Empty.PadLeft(80, '=')); //Console.WriteLine("Name: {0}", adapter.Name); //Console.WriteLine(adapter.Description); //Console.WriteLine(String.Empty.PadLeft(80, '-')); //Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType); //Console.WriteLine(" Operational status ...................... : {0}", adapter.OperationalStatus); //Console.WriteLine(" Physical Address ........................ : {0}", adapter.GetPhysicalAddress().ToString()); //Console.WriteLine(" Is receive only.......................... : {0}", adapter.IsReceiveOnly); //Console.WriteLine(" Multicast................................ : {0}", adapter.SupportsMulticast); //Console.WriteLine(" DNS suffix .............................. : {0}", properties.DnsSuffix); //Console.WriteLine(" DNS enabled ............................. : {0}", properties.IsDnsEnabled); //Console.WriteLine(" Dynamically configured DNS .............. : {0}", properties.IsDynamicDnsEnabled); SetTextLine(String.Empty.PadLeft(80, '=')); SetTextLine(String.Format("Name: {0}", adapter.Name)); SetTextLine(adapter.Description); SetTextLine(String.Empty.PadLeft(80, '_')); SetTextLine(String.Format(" ID ...................................... : {0}", adapter.Id)); SetTextLine(String.Format(" Interface type .......................... : {0}", adapter.NetworkInterfaceType)); SetTextLine(String.Format(" Operational status ...................... : {0}", adapter.OperationalStatus)); SetTextLine(String.Format(" Physical Address ........................ : {0}", adapter.GetPhysicalAddress().ToString())); SetTextLine(String.Format(" Is receive only.......................... : {0}", adapter.IsReceiveOnly)); SetTextLine(String.Format(" Multicast................................ : {0}", adapter.SupportsMulticast)); SetTextLine(String.Format(" DNS suffix .............................. : {0}", properties.DnsSuffix)); SetTextLine(String.Format(" DNS enabled ............................. : {0}", properties.IsDnsEnabled)); SetTextLine(String.Format(" Dynamically configured DNS .............. : {0}", properties.IsDynamicDnsEnabled)); string versions = ""; // Create a display string for the supported IP versions. if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { versions = "IPv4"; IPv4InterfaceStatistics stats = adapter.GetIPv4Statistics(); IPv4InterfaceProperties p = properties.GetIPv4Properties(); //Console.WriteLine(" IP version .............................. : {0}", versions); //Console.WriteLine(" Speed .................................: {0}", adapter.Speed); //Console.WriteLine(" Output queue length....................: {0}", stats.OutputQueueLength); SetTextLine(String.Format(" IP version .............................. : {0}", versions)); SetTextLine(String.Format(" Speed .................................: {0}", adapter.Speed)); SetTextLine(String.Format(" Output queue length....................: {0}", stats.OutputQueueLength)); if (p != null) { //Console.WriteLine(" Index ................................ : {0}", p.Index); //Console.WriteLine(" MTU .................................. : {0}", p.Mtu); //Console.WriteLine(" APIPA active.......................... : {0}", p.IsAutomaticPrivateAddressingActive); //Console.WriteLine(" APIPA enabled......................... : {0}", p.IsAutomaticPrivateAddressingEnabled); //Console.WriteLine(" Forwarding enabled.................... : {0}", p.IsForwardingEnabled); //Console.WriteLine(" Uses WINS ............................ : {0}", p.UsesWins); SetTextLine(String.Format(" Index ................................ : {0}", p.Index)); SetTextLine(String.Format(" MTU .................................. : {0}", p.Mtu)); SetTextLine(String.Format(" APIPA active.......................... : {0}", p.IsAutomaticPrivateAddressingActive)); SetTextLine(String.Format(" APIPA enabled......................... : {0}", p.IsAutomaticPrivateAddressingEnabled)); SetTextLine(String.Format(" DHCP enabled.......................... : {0}", p.IsDhcpEnabled)); SetTextLine(String.Format(" Forwarding enabled.................... : {0}", p.IsForwardingEnabled)); SetTextLine(String.Format(" Uses WINS ............................ : {0}", p.UsesWins)); } } if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { if (versions.Length > 0) { versions += " "; } versions += "IPv6"; //Console.WriteLine(" IP version .............................. : {0}", versions); SetTextLine(String.Format(" IP version .............................. : {0}", versions)); } //SetTextLine(String.Format("{0}","")); foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { SetTextLine(String.Format(" IP Address .............................. : {0}", ip.Address.ToString())); SetTextLine(String.Format(" Subnet Mask ............................. : {0}", ip.IPv4Mask == null ? "No subnet defined" : ip.IPv4Mask.ToString())); } else { SetTextLine(String.Format(" IP Address .............................. : {0}", ip.Address.ToString())); SetTextLine(String.Format(" Subnet Mask ............................. : {0}", ip.IPv4Mask == null ? "No subnet defined" : ip.IPv4Mask.ToString())); } //SetTextLine(String.Format(" IP Address .............................. : {0}", ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? ip.Address.ToString(): ip.Address.ToString())); } foreach (GatewayIPAddressInformation gipi in adapter.GetIPProperties().GatewayAddresses) { SetTextLine(String.Format(" Default Gateway ......................... : {0}", gipi.Address.ToString())); } } }
public override void Update() { try { if (NetworkInterface == null) { return; } long newTick = Stopwatch.GetTimestamp(); double dt = new TimeSpan(newTick - _lastTick).TotalSeconds; IPv4InterfaceStatistics interfaceStats = NetworkInterface.GetIPv4Statistics(); // Report out the number of GB (2^30 Bytes) that this interface has up/downloaded. Note // that these values can reset back at zero (eg: after waking from sleep). _dataUploaded.Value = (interfaceStats.BytesSent / (double)0x40000000); _dataDownloaded.Value = (interfaceStats.BytesReceived / (double)0x40000000); // Detect a reset in interface stats if the new total is less than what was previously // seen. While setting the previous values to zero doesn't encapsulate the value the // instant before the reset, it is the best approximation we have. if (interfaceStats.BytesSent < _bytesUploaded || interfaceStats.BytesReceived < _bytesDownloaded) { _bytesUploaded = 0; _bytesDownloaded = 0; } long dBytesUploaded = interfaceStats.BytesSent - _bytesUploaded; long dBytesDownloaded = interfaceStats.BytesReceived - _bytesDownloaded; // Upload and download speeds are reported as the number of mbytes transfered over the // time difference since the last report. In this way, the values represent the average // number of bytes up/downloaded in a second. _uploadSpeed.Value = (dBytesUploaded / dt / (1024 * 1024)); _downloadSpeed.Value = (dBytesDownloaded / dt / (1024 * 1024)); // Network speed is in bits per second, so when calculating the load on the NIC we first // grab the total number of bits up/downloaded long dbits = (dBytesUploaded + dBytesDownloaded) * 8; // Converts the ratio of total bits transferred over time over theoretical max bits // transfer rate into a percentage load double load = (dbits / dt / NetworkInterface.Speed) * 100; // Finally clamp the value between 0% and 100% to avoid reporting nonsensical numbers _networkUtilization.Value = (float)Math.Min(Math.Max(load, 0), 100); // Store the recorded values and time, so they can be used in the next update _bytesUploaded = interfaceStats.BytesSent; _bytesDownloaded = interfaceStats.BytesReceived; _lastTick = newTick; } catch (NetworkInformationException networkInformationException) when(unchecked (networkInformationException.HResult == (int)0x80004005)) { foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { if (networkInterface.Id.Equals(NetworkInterface?.Id)) { NetworkInterface = networkInterface; break; } } } }
/// <summary> /// リスト更新 /// </summary> public void UpdateList() { // 更新開始 this.BeginUpdate(); // リスト削除 Delete(); // すべてのネットワークインターフェイスを取得する NetworkInterface[] _NetworkInterfaceList = NetworkInterface.GetAllNetworkInterfaces(); // すべてのネットワークインターフェイス分繰り返し foreach (NetworkInterface _NetworkInterface in _NetworkInterfaceList) { Debug.WriteLine("----------------------------------------"); Debug.WriteLine("ネットワークインターフェイス情報"); Debug.WriteLine("----------------------------------------"); Debug.WriteLine("名称 : " + _NetworkInterface.Name); Debug.WriteLine("説明 : " + _NetworkInterface.Description); Debug.WriteLine("I/F種類 : " + _NetworkInterface.NetworkInterfaceType.ToString()); Debug.WriteLine("最大速度 : " + (_NetworkInterface.Speed / 1000000).ToString() + "Mbps"); Debug.WriteLine("macアドレス: " + _NetworkInterface.GetPhysicalAddress().ToString()); Debug.WriteLine("送信byte数 : " + _NetworkInterface.GetIPv4Statistics().BytesSent.ToString()); Debug.WriteLine("受信byte数 : " + _NetworkInterface.GetIPv4Statistics().BytesReceived.ToString()); // 登録がなければリストに追加 ListViewItem _ListViewItem = this.FindItemWithText(_NetworkInterface.Name); if (_ListViewItem == null) { _ListViewItem = this.Items.Add(_NetworkInterface.Name); for (int i = 1; i < this.Columns.Count; i++) { _ListViewItem.SubItems.Add(""); } } else { for (int i = 1; i < this.Columns.Count; i++) { _ListViewItem.SubItems[i].Text = ""; } } int _SubItemsIndex = 1; _ListViewItem.SubItems[_SubItemsIndex].Text += _NetworkInterface.Description; _ListViewItem.SubItems[_SubItemsIndex + 1].Text += _NetworkInterface.NetworkInterfaceType.ToString(); _ListViewItem.SubItems[_SubItemsIndex + 2].Text += (_NetworkInterface.Speed / 1000000).ToString() + "Mbps"; _ListViewItem.SubItems[_SubItemsIndex + 3].Text += _NetworkInterface.GetPhysicalAddress().ToString(); _SubItemsIndex += 4; //ネットワーク接続しているか調べる if (_NetworkInterface.OperationalStatus == OperationalStatus.Up && _NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback && _NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel) { // 接続している場合 // 構成情報、アドレス情報を取得する IPInterfaceProperties _IPInterfaceProperties = _NetworkInterface.GetIPProperties(); if (_IPInterfaceProperties != null) { foreach (UnicastIPAddressInformation _UnicastIPAddressInformation in _IPInterfaceProperties.UnicastAddresses) { _ListViewItem.SubItems[_SubItemsIndex].Text += _UnicastIPAddressInformation.Address + " "; _ListViewItem.SubItems[_SubItemsIndex + 1].Text += _UnicastIPAddressInformation.IPv4Mask + " "; Debug.WriteLine("ユニキャストアドレス:{0}", _UnicastIPAddressInformation.Address); Debug.WriteLine("IPv4マスク:{0}", _UnicastIPAddressInformation.IPv4Mask); } _SubItemsIndex += 2; foreach (IPAddress _IPAddress in _IPInterfaceProperties.DnsAddresses) { _ListViewItem.SubItems[_SubItemsIndex].Text += _IPAddress.ToString() + " "; Debug.WriteLine("DNS:" + _IPAddress.ToString()); } _SubItemsIndex += 1; foreach (IPAddress _IPAddress in _IPInterfaceProperties.DhcpServerAddresses) { _ListViewItem.SubItems[_SubItemsIndex].Text += _IPAddress.ToString() + " "; Debug.WriteLine("DHCP:" + _IPAddress.ToString()); } _SubItemsIndex += 1; foreach (GatewayIPAddressInformation _IPAddress in _IPInterfaceProperties.GatewayAddresses) { _ListViewItem.SubItems[_SubItemsIndex].Text += _IPAddress.Address.ToString() + " "; Debug.WriteLine("Gateway:" + _IPAddress.Address.ToString()); } _SubItemsIndex += 1; foreach (System.Net.IPAddress _IPAddress in _IPInterfaceProperties.WinsServersAddresses) { _ListViewItem.SubItems[_SubItemsIndex].Text += _IPAddress.ToString() + " "; Debug.WriteLine("WINS:" + _IPAddress.ToString()); } _SubItemsIndex += 1; } // IPv4の統計情報を表示する if (_NetworkInterface.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceStatistics _IPv4InterfaceStatistics = _NetworkInterface.GetIPv4Statistics(); _ListViewItem.SubItems[_SubItemsIndex].Text += _IPv4InterfaceStatistics.BytesReceived.ToString("#,0") + " "; _ListViewItem.SubItems[_SubItemsIndex + 1].Text += _IPv4InterfaceStatistics.BytesSent.ToString("#,0") + " "; _ListViewItem.SubItems[_SubItemsIndex + 1].Text += _IPv4InterfaceStatistics.BytesReceived.ToString("#,0") + " "; _ListViewItem.SubItems[_SubItemsIndex + 1].Text += _IPv4InterfaceStatistics.BytesSent.ToString("#,0") + " "; Debug.WriteLine("受信バイト数:" + _IPv4InterfaceStatistics.BytesReceived); Debug.WriteLine("送信バイト数:" + _IPv4InterfaceStatistics.BytesSent); Debug.WriteLine("受信したユニキャストパケット数:" + _IPv4InterfaceStatistics.UnicastPacketsReceived); Debug.WriteLine("送信したユニキャストパケット数:" + _IPv4InterfaceStatistics.UnicastPacketsSent); } Debug.WriteLine(""); } else { // 接続していない場合 } } // 更新終了 this.EndUpdate(); }