public static bool IsValidNetworkAdapter(NetworkAdapter net) { //DebugLog("IsValidNetworkAdapter - Checking if adapter is valid: Manufacturer=" + net.Manufacturer + " PNPDeviceID= " + net.PNPDeviceID + " Name=" + net.Name + " ProductName=" + net.ProductName + " Caption=" + net.Caption + " Description=" + net.Description); bool flag2 = ((((StringType.StrCmp(net.Manufacturer, "", false) > 0) && net.Installed) && ((StringType.StrCmp(net.PNPDeviceID, "", false) > 0) && (net.Name.ToUpper().IndexOf("VPN") == -1))) && (((net.ProductName.ToUpper().IndexOf("VPN") == -1) && (net.Caption.ToUpper().IndexOf("VPN") == -1)) && ((net.Description.ToUpper().IndexOf("VPN") == -1) && (net.Name.ToUpper().IndexOf("VIRTUAL") == -1)))) && ((((net.ProductName.ToUpper().IndexOf("VIRTUAL") == -1) && (net.Caption.ToUpper().IndexOf("VIRTUAL") == -1)) && ((net.Description.ToUpper().IndexOf("VIRTUAL") == -1) && (net.Name.ToUpper().IndexOf("MINIPORT") == -1))) && (((net.ProductName.ToUpper().IndexOf("MINIPORT") == -1) && (net.Caption.ToUpper().IndexOf("MINIPORT") == -1)) && (net.Description.ToUpper().IndexOf("MINIPORT") == -1))); //DebugLog("IsValidNetworkAdapter result=" + flag2.ToString()); return flag2; }
/// <summary> /// Specific constructor for ComputationalClient class. Allows to execute client's correctly. Also creates NetworkAdapter inside. Throws ArgumentNullException when incorrent inputs. /// </summary> /// <param name="serverName"> String value of a server address name. Cannot be empty. </param> /// <param name="port"> Port on which server is listening. Cannot be negative. </param> /// <param name="problemType"> String value of name of a problem type. For example 'drvp'. Cannot be empty. </param> /// <param name="solvingTimeout"> Time that client wait for solution. After it clients terminates. </param> /// <param name="data"> Data that is sent to server. </param> public Client(string serverName, int port, string problemType, ulong solvingTimeout, byte[] data) { _networkAdapter = new NetworkAdapter(serverName, port); if(problemType == null || serverName == null || port < 0) throw new ArgumentNullException(); _solutionsList = new List<byte[]>(); _problemType = problemType; _solvingTimeout = solvingTimeout; _data = data; _working = true; }
protected override void OnStart() { base.OnStart(); IPEndPoint ep; IPAddress local; string iface; uint? mtu; try { ep = ResolveHost(); if (!AddressFamilySupported(ep.AddressFamily)) { throw new PeachException(string.Format("The resolved IP '{0}' for host '{1}' is not compatible with the {2} publisher.", ep, Host, _type)); } local = Interface; if (Interface == null) { local = GetLocalIp(ep); } if (local.IsIPv6LinkLocal && local.ScopeId == 0) { local = GetScopeId(local); Logger.Trace("Resolved link-local interface IP for {0} socket to {1}.", _type, local); } try { iface = GetInterfaceName(local); if (iface == null) { throw new PeachException("Could not resolve interface name for local IP '{0}'.".Fmt(local)); } using (var cfg = NetworkAdapter.CreateInstance(iface)) { mtu = cfg.MTU; } } catch (Exception ex) { string msg = ex.Message; if (ex is TypeInitializationException || ex is TargetInvocationException) { msg = ex.InnerException.Message; } iface = local.ToString(); mtu = null; Logger.Debug("Could not query the MTU of '{0}'. {1}", iface, msg); } } catch (Exception ex) { Logger.Error("Unable to start {0} publisher for {1}:{2}. {3}.", _type, Host, Port, ex.Message); throw new SoftException(ex); } _remoteEp = ep; _localIp = local; _iface = iface; _mtu = mtu; _origMtu = mtu; }
public async Task <Unit> Handle(UpdateHardwareCommand request, CancellationToken cancellationToken) { var entity = await _context.Hardwares.FindAsync(request.Hardware.Id); var hardware = request.Hardware; switch (hardware.HardwareType) { case HardwareType.Cabinet: ((Cabinet)entity).Position = ((CabinetDto)hardware).Position; ((Cabinet)entity).SerialNumber = ((CabinetDto)hardware).SerialNumber; ((Cabinet)entity).Constructed = ((CabinetDto)hardware).Constructed; ((Cabinet)entity).ConstructedBy = ((CabinetDto)hardware).ConstructedBy; break; case HardwareType.FlowComputer: ((FlowComputer)entity).Position = ((FlowComputerDto)hardware).Position; ((FlowComputer)entity).SerialNumber = ((FlowComputerDto)hardware).SerialNumber; ((FlowComputer)entity).DeviceModel = ((FlowComputerDto)hardware).DeviceModel; ((FlowComputer)entity).AssemblyVersion = ((FlowComputerDto)hardware).AssemblyVersion; ((FlowComputer)entity).CRC32 = ((FlowComputerDto)hardware).CRC32; ((FlowComputer)entity).IP = ((FlowComputerDto)hardware).IP; ((FlowComputer)entity).LastConfigDate = ((FlowComputerDto)hardware).LastConfigDate; break; case HardwareType.Flowmeter: ((Flowmeter)entity).Position = ((FlowmeterDto)hardware).Position; ((Flowmeter)entity).SerialNumber = ((FlowmeterDto)hardware).SerialNumber; ((Flowmeter)entity).DeviceType = ((FlowmeterDto)hardware).DeviceType; ((Flowmeter)entity).DeviceModel = ((FlowmeterDto)hardware).DeviceModel; ((Flowmeter)entity).MinValue = ((FlowmeterDto)hardware).MinValue; ((Flowmeter)entity).MaxValue = ((FlowmeterDto)hardware).MaxValue; ((Flowmeter)entity).EU = ((FlowmeterDto)hardware).EU; ((Flowmeter)entity).Kfactor = ((FlowmeterDto)hardware).Kfactor; ((Flowmeter)entity).SignalType = ((FlowmeterDto)hardware).SignalType; ((Flowmeter)entity).Settings.Address = ((FlowmeterDto)hardware).ModbusSettings.Address; ((Flowmeter)entity).Settings.BoudRate = ((FlowmeterDto)hardware).ModbusSettings.BoudRate; ((Flowmeter)entity).Settings.Parity = ((FlowmeterDto)hardware).ModbusSettings.Parity.ToString(); ((Flowmeter)entity).Settings.DataBits = ((FlowmeterDto)hardware).ModbusSettings.DataBits; ((Flowmeter)entity).Settings.StopBit = ((FlowmeterDto)hardware).ModbusSettings.StopBit; break; case HardwareType.Network: ((NetworkHardware)entity).Position = ((NetworkHardwareDto)hardware).Position; ((NetworkHardware)entity).SerialNumber = ((NetworkHardwareDto)hardware).SerialNumber; ((NetworkHardware)entity).DeviceType = ((NetworkHardwareDto)hardware).DeviceType; ((NetworkHardware)entity).DeviceModel = ((NetworkHardwareDto)hardware).DeviceModel; ((NetworkHardware)entity).Mask = ((NetworkHardwareDto)hardware).Mask; ((NetworkHardware)entity).NetworkDevices.Clear(); foreach (var item in ((NetworkHardwareDto)hardware).NetworkDevices) { var device = new NetworkDevice { Name = item.Name, IP = item.IP, MacAddress = item.MacAddress }; ((NetworkHardware)entity).NetworkDevices.Add(device); } ; break; case HardwareType.PLC: ((PLC)entity).Position = ((PlcDto)hardware).Position; ((PLC)entity).SerialNumber = ((PlcDto)hardware).SerialNumber; ((PLC)entity).DeviceModel = ((PlcDto)hardware).DeviceModel; ((PLC)entity).AssemblyVersion = ((PlcDto)hardware).AssemblyVersion; ((PLC)entity).IP = ((PlcDto)hardware).IP; break; case HardwareType.Pressure: ((Pressure)entity).Position = ((PressureDto)hardware).Position; ((Pressure)entity).SerialNumber = ((PressureDto)hardware).SerialNumber; ((Pressure)entity).DeviceType = ((PressureDto)hardware).DeviceType; ((Pressure)entity).DeviceModel = ((PressureDto)hardware).DeviceModel; ((Pressure)entity).MinValue = ((PressureDto)hardware).MinValue; ((Pressure)entity).MaxValue = ((PressureDto)hardware).MaxValue; ((Pressure)entity).EU = ((PressureDto)hardware).EU; ((Pressure)entity).SignalType = ((PressureDto)hardware).SignalType; break; case HardwareType.DiffPressure: ((DiffPressure)entity).Position = ((DiffPressureDto)hardware).Position; ((DiffPressure)entity).SerialNumber = ((DiffPressureDto)hardware).SerialNumber; ((DiffPressure)entity).DeviceType = ((DiffPressureDto)hardware).DeviceType; ((DiffPressure)entity).DeviceModel = ((DiffPressureDto)hardware).DeviceModel; ((DiffPressure)entity).MinValue = ((DiffPressureDto)hardware).MinValue; ((DiffPressure)entity).MaxValue = ((DiffPressureDto)hardware).MaxValue; ((DiffPressure)entity).EU = ((DiffPressureDto)hardware).EU; ((DiffPressure)entity).SignalType = ((DiffPressureDto)hardware).SignalType; break; case HardwareType.Temperature: ((Temperature)entity).Position = ((TemperatureDto)hardware).Position; ((Temperature)entity).SerialNumber = ((TemperatureDto)hardware).SerialNumber; ((Temperature)entity).DeviceType = ((TemperatureDto)hardware).DeviceType; ((Temperature)entity).DeviceModel = ((TemperatureDto)hardware).DeviceModel; ((Temperature)entity).MinValue = ((TemperatureDto)hardware).MinValue; ((Temperature)entity).MaxValue = ((TemperatureDto)hardware).MaxValue; ((Temperature)entity).EU = ((TemperatureDto)hardware).EU; ((Temperature)entity).SignalType = ((TemperatureDto)hardware).SignalType; break; case HardwareType.GasAnalyzer: ((GasAnalyzer)entity).Position = ((GasAnalyzerDto)hardware).Position; ((GasAnalyzer)entity).SerialNumber = ((GasAnalyzerDto)hardware).SerialNumber; ((GasAnalyzer)entity).DeviceType = ((GasAnalyzerDto)hardware).DeviceType; ((GasAnalyzer)entity).DeviceModel = ((GasAnalyzerDto)hardware).DeviceModel; ((GasAnalyzer)entity).MinValue = ((GasAnalyzerDto)hardware).MinValue; ((GasAnalyzer)entity).MaxValue = ((GasAnalyzerDto)hardware).MaxValue; ((GasAnalyzer)entity).EU = ((GasAnalyzerDto)hardware).EU; ((GasAnalyzer)entity).SignalType = ((GasAnalyzerDto)hardware).SignalType; break; case HardwareType.APC: ((APC)entity).Position = ((ApcDto)hardware).Position; ((APC)entity).SerialNumber = ((ApcDto)hardware).SerialNumber; ((APC)entity).DeviceType = ((ApcDto)hardware).DeviceType; ((APC)entity).DeviceModel = ((ApcDto)hardware).DeviceModel; break; case HardwareType.FireSensor: ((FireSensor)entity).Position = ((FireSensorDto)hardware).Position; ((FireSensor)entity).SerialNumber = ((FireSensorDto)hardware).SerialNumber; ((FireSensor)entity).DeviceType = ((FireSensorDto)hardware).DeviceType; ((FireSensor)entity).DeviceModel = ((FireSensorDto)hardware).DeviceModel; break; case HardwareType.FireModule: ((FireModule)entity).Position = ((FireModuleDto)hardware).Position; ((FireModule)entity).SerialNumber = ((FireModuleDto)hardware).SerialNumber; ((FireModule)entity).DeviceType = ((FireModuleDto)hardware).DeviceType; break; case HardwareType.InformPanel: ((InformPanel)entity).Position = ((InformPanelDto)hardware).Position; ((InformPanel)entity).SerialNumber = ((InformPanelDto)hardware).SerialNumber; ((InformPanel)entity).DeviceType = ((InformPanelDto)hardware).DeviceType; ((InformPanel)entity).DeviceModel = ((InformPanelDto)hardware).DeviceModel; ((InformPanel)entity).PanelType = ((InformPanelDto)hardware).PanelType; break; case HardwareType.Valve: ((Valve)entity).Position = ((ValveDto)hardware).Position; ((Valve)entity).SerialNumber = ((ValveDto)hardware).SerialNumber; ((Valve)entity).DeviceType = ((ValveDto)hardware).DeviceType; ((Valve)entity).DeviceModel = ((ValveDto)hardware).DeviceModel; ((Valve)entity).SignalType = ((ValveDto)hardware).SignalType; ((Valve)entity).Settings.Address = ((ValveDto)hardware).ModbusSettings.Address; ((Valve)entity).Settings.BoudRate = ((ValveDto)hardware).ModbusSettings.BoudRate; ((Valve)entity).Settings.Parity = ((ValveDto)hardware).ModbusSettings.Parity.ToString(); ((Valve)entity).Settings.DataBits = ((ValveDto)hardware).ModbusSettings.DataBits; ((Valve)entity).Settings.StopBit = ((ValveDto)hardware).ModbusSettings.StopBit; break; case HardwareType.ARM: ((ARM)entity).Position = ((ArmDto)hardware).Position; ((ARM)entity).Name = ((ArmDto)hardware).Name; ((ARM)entity).SerialNumber = ((ArmDto)hardware).SerialNumber; ((ARM)entity).Monitor = ((ArmDto)hardware).Monitor; ((ARM)entity).MonitorSN = ((ArmDto)hardware).MonitorSN; ((ARM)entity).Keyboard = ((ArmDto)hardware).Keyboard; ((ARM)entity).KeyboardSN = ((ArmDto)hardware).KeyboardSN; ((ARM)entity).Mouse = ((ArmDto)hardware).Mouse; ((ARM)entity).MouseSN = ((ArmDto)hardware).MouseSN; ((ARM)entity).OS = ((ArmDto)hardware).OS; ((ARM)entity).ProductKeyOS = ((ArmDto)hardware).ProductKeyOS; ((ARM)entity).HasRAID = ((ArmDto)hardware).HasRAID; ((ARM)entity).NetworkAdapters.Clear(); foreach (var item in ((ArmDto)hardware).NetworkAdapters) { var device = new NetworkAdapter { IP = item.IP, MacAddress = item.MacAddress }; ((ARM)entity).NetworkAdapters.Add(device); } ; break; } try { await _context.SaveChangesAsync(cancellationToken); } catch (System.Exception ex) { throw ex; } return(Unit.Value); }
/// <summary> /// class constructor /// </summary> public NetworkAdapters() { try { ManagementObjectSearcher _adapters = new ManagementObjectSearcher("select * from Win32_NetworkAdapter"); if (_adapters.Get().Count == -1) { throw new Exception("Could not get NetworkAdapter(s) information."); } // Iterate over network adapters foreach (ManagementObject _adapter in _adapters.Get()) { NetworkAdapter _adapter_info = new NetworkAdapter(); // iterate over network adapter settings foreach (PropertyData PC in _adapter.Properties) { if (PC.Value != null) { if (PC.Name == "NetConnectionID") { _adapter_info.Adapter_Display_Name = (string)PC.Value; } if (PC.Name == "MACAddress") { _adapter_info.Adapter_MAC_Address = (string)PC.Value; } if (PC.Name == "Manufacturer") { _adapter_info.Adapter_Manufacturer = (string)PC.Value; } if (PC.Name == "Name") { _adapter_info.Adapter_Name = (string)PC.Value; } if (PC.Name == "PhysicalAdapter") { _adapter_info.Is_A_Physical_Adapter = (bool)PC.Value; } if (PC.Name == "NetEnabled") { _adapter_info.Is_A_Physical_Adapter = (bool)PC.Value; } if (PC.Name == "Index") { _adapter_info.Adapter_Index = (uint)PC.Value; } if (PC.Name == "InterfaceIndex") { _adapter_info.Adapter_Interface_Index = (uint)PC.Value; } } } // Get configuration settings for each network adapter ManagementObject _adapters_settings = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration where Index=" + _adapter_info.Adapter_Index + " And InterfaceIndex=" + _adapter_info.Adapter_Interface_Index).Get().Cast <ManagementObject>().First(); // Iterate over network adapter configuration settings foreach (PropertyData PC in _adapters_settings.Properties) { if (PC.Value != null) { if (PC.Name == "DHCPEnabled") { _adapter_info.Adapter_DHCP_Enabled = (bool)PC.Value; } if (PC.Name == "IPFilterSecurityEnabled") { _adapter_info.Adapter_IP_Filter_Enabled = (bool)PC.Value; } if (PC.Name == "IPAddress") { _adapter_info.Adapter_IP_Address = ((string[])PC.Value).ElementAt(0); } if (PC.Name == "IPSubnet") { _adapter_info.Adapter_Subnet_IP = ((string[])PC.Value).ElementAt(0); } } } // Add current network adapter to the network adapters list Network_Adapters.Add(_adapter_info); } } catch (Exception ex) { throw ex; } }
public void GetActiveConnectionIDTest() { Console.WriteLine(NetworkAdapter.GetActiveConnectionID()); }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); DatagramSocket listener = new DatagramSocket(); listener.MessageReceived += MessageReceived; if (!String.IsNullOrWhiteSpace(InboundBufferSize.Text)) { uint inboundBufferSize = 0; if (!uint.TryParse(InboundBufferSize.Text, out inboundBufferSize)) { rootPage.NotifyUser( "Please provide a positive numeric Inbound buffer size.", NotifyType.ErrorMessage); return; } try { // Running both client and server on localhost will most likely not reach the buffer limit. listener.Control.InboundBufferSizeInBytes = inboundBufferSize; } catch (ArgumentException) { rootPage.NotifyUser("Please provide a valid Inbound buffer size.", NotifyType.ErrorMessage); return; } } LocalHostItem selectedLocalHost = null; if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny.IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overriden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; await listener.BindServiceNameAsync(ServiceNameForListener.Text, selectedAdapter); rootPage.NotifyUser( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
private void SubnetRemoved(NetworkAdapter aAdapter) { Console.WriteLine(String.Format("SubnetRemoved: {0}", aAdapter.Name())); }
public Speed_indicator(NetworkAdapter networkAdapter = null) { InitializeComponent(); adapter = networkAdapter; }
/// <summary> /// Specific constructor for ComputationalNode class. Allows to execute node's correctly. /// </summary> /// <param name="serverName">String value of a server address name. </param> /// <param name="port">Port on which server is listening.</param> public ComputationalNode(string serverName, int port) { if (serverName == null || port < 0) throw new ArgumentNullException(); networkAdapter = new NetworkAdapter(serverName, port); }
public static NetworkAdapter CreateNetworkAdapter(global::System.Collections.ObjectModel.ObservableCollection<IPAddress> iPAddresses) { NetworkAdapter networkAdapter = new NetworkAdapter(); if ((iPAddresses == null)) { throw new global::System.ArgumentNullException("iPAddresses"); } networkAdapter.IPAddresses = iPAddresses; return networkAdapter; }
/// <summary> /// Retrieves the network adapters. /// </summary> /// <returns></returns> public List <NetworkAdapter> RetrieveAdapters() { var result = new List <NetworkAdapter>(); var interfacesOutput = ProcessRunner.GetProcessOutputAsync("ifconfig").Result; var wlanOutput = ProcessRunner.GetProcessOutputAsync("iwconfig") .Result.Split('\n') .Where(x => x.Contains("no wireless extensions.") == false) .ToArray(); var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); for (var i = 0; i < outputLines.Length; i++) { var line = outputLines[i]; if (line[0] >= 'a' && line[0] <= 'z') { var adapter = new NetworkAdapter { Name = line.Substring(0, line.IndexOf(' ')) }; if (line.IndexOf(HWaddr) > 0) { var startIndexHwd = line.IndexOf(HWaddr) + HWaddr.Length; adapter.MacAddress = line.Substring(startIndexHwd).Trim(); } if (i + 1 >= outputLines.Length) { break; } // move next line line = outputLines[++i].Trim(); if (line.StartsWith("inet addr:")) { var tempIP = line.Replace("inet addr:", string.Empty).Trim(); tempIP = tempIP.Substring(0, tempIP.IndexOf(' ')); IPAddress outValue; if (IPAddress.TryParse(tempIP, out outValue)) { adapter.IPv4 = outValue; } if (i + 1 >= outputLines.Length) { break; } line = outputLines[++i].Trim(); } if (line.StartsWith("inet6 addr:")) { var tempIP = line.Replace("inet6 addr:", string.Empty).Trim(); tempIP = tempIP.Substring(0, tempIP.IndexOf('/')); IPAddress outValue; if (IPAddress.TryParse(tempIP, out outValue)) { adapter.IPv6 = outValue; } } var wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name)); if (wlanInfo != null) { adapter.IsWireless = true; var startIndex = wlanInfo.IndexOf(EssidTag) + EssidTag.Length; adapter.AccessPointName = wlanInfo.Substring(startIndex).Replace("\"", string.Empty); } result.Add(adapter); } } return(result.OrderBy(x => x.Name).ToList()); }
public ModuleConfiguration(NetworkAdapter na) { this.na = na; moduleOrder = na.modules.GetModuleOrder(); InitializeComponent(); }
public void SetAdapter(NetworkAdapter Adapter) { CheckAllowSendAll(); }
public override List <NetworkAdapter> GetNetworkAdapterList() { List <NetworkAdapter> networkAdapterList = new List <NetworkAdapter>(); using ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE PhysicalAdapter=True AND MACAddress IS NOT NULL"); foreach (ManagementObject mo in mos.Get()) { NetworkAdapter networkAdapter = new NetworkAdapter { AdapterType = GetPropertyString(mo["AdapterType"]), Caption = GetPropertyString(mo["Caption"]), Description = GetPropertyString(mo["Description"]), MACAddress = GetPropertyString(mo["MACAddress"]), Manufacturer = GetPropertyString(mo["Manufacturer"]), Name = GetPropertyString(mo["Name"]), NetConnectionID = GetPropertyString(mo["NetConnectionID"]), ProductName = GetPropertyString(mo["ProductName"]), Speed = GetPropertyValue <ulong>(mo["Speed"]) }; using ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher($"SELECT * FROM Win32_PerfFormattedData_Tcpip_NetworkAdapter WHERE Name = '{networkAdapter.Name.Replace("(", "[").Replace(")", "]")}'"); foreach (ManagementObject managementObject in managementObjectSearcher.Get()) { networkAdapter.BytesSentPersec = GetPropertyValue <ulong>(managementObject["BytesSentPersec"]); networkAdapter.BytesReceivedPersec = GetPropertyValue <ulong>(managementObject["BytesReceivedPersec"]); } IPAddress address; foreach (ManagementObject configuration in mo.GetRelated("Win32_NetworkAdapterConfiguration")) { foreach (string str in GetPropertyArray <string>(configuration["DefaultIPGateway"])) { if (IPAddress.TryParse(str, out address)) { networkAdapter.DefaultIPGatewayList.Add(address); } } if (IPAddress.TryParse(GetPropertyString(configuration["DHCPServer"]), out address)) { networkAdapter.DHCPServer = address; } foreach (string str in GetPropertyArray <string>(configuration["DNSServerSearchOrder"])) { if (IPAddress.TryParse(str, out address)) { networkAdapter.DNSServerSearchOrderList.Add(address); } } foreach (string str in GetPropertyArray <string>(configuration["IPAddress"])) { if (IPAddress.TryParse(str, out address)) { networkAdapter.IPAddressList.Add(address); } } foreach (string str in GetPropertyArray <string>(configuration["IPSubnet"])) { if (IPAddress.TryParse(str, out address)) { networkAdapter.IPSubnetList.Add(address); } } } networkAdapterList.Add(networkAdapter); } return(networkAdapterList); }
private void NetworkAdapterChanged(NetworkAdapter aAdapter) { Console.WriteLine(String.Format("NetworkAdapterChanged: {0}", aAdapter.Name())); }
/// <summary> /// The start tunnel. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public static bool StartTunnel() { if (!CommonLibrary.Common.IsValidIpSubnet(IpSubnet)) { return(false); } AdapterAddressRange = CommonLibrary.Common.MergeIpIntoIpSubnet( AdapterAddressRange, IpSubnet, IPAddress.Parse("10.0.0.1")); IPAddress addressGateWay = CommonLibrary.Common.MergeIpIntoIpSubnet( AdapterAddressRange, IpSubnet, IPAddress.Parse("10.0.0.2")); NetworkAdapter net = TapAdapter.InstallAnAdapter(TunnelName); if (net == null) { return(false); } if ( !Tun2Socks.StartTun2Socks( net, AdapterAddressRange, IpSubnet, addressGateWay, SocksProxyEndPoint)) { return(false); } NetworkAdapterConfiguration netconfig = net.GetNetworkConfiguration(); if (netconfig == null) { return(false); } int timeout = 30; timeout = timeout / 3; string dnsString = string.Empty; if (AutoDnsResolving && AutoDnsResolvingAddress != null) { Dns2Socks.StartDns2Socks(AutoDnsResolvingAddress, SocksProxyEndPoint); dnsString = SocksProxyEndPoint.Address.ToString(); } else if (DnsResolvingAddress != null && DnsResolvingAddress2 != null) { dnsString = DnsResolvingAddress + "," + DnsResolvingAddress2; } else if (DnsResolvingAddress != null) { dnsString = DnsResolvingAddress.ToString(); } else if (DnsResolvingAddress2 != null) { dnsString = DnsResolvingAddress2.ToString(); } while (true) { if (netconfig.SetIpAddresses(AdapterAddressRange.ToString(), IpSubnet.ToString()) && netconfig.SetDnsSearchOrder(dnsString)) { break; } if (timeout == 0) { return(false); } timeout--; Thread.Sleep(3000); } IP4RouteTable.AddChangeRouteRule( IPAddress.Parse("0.0.0.0"), addressGateWay, 2, IPAddress.Parse("0.0.0.0"), (int)net.InterfaceIndex); int lowestMetric = 1000; IP4RouteTable me = null; List <IP4RouteTable> internetRules = new List <IP4RouteTable>(); foreach (IP4RouteTable r in IP4RouteTable.GetCurrentTable().ToArray()) { if (r.Destination == "0.0.0.0") { if (r.InterfaceIndex == net.InterfaceIndex) { me = r; } else { internetRules.Add(r); if (lowestMetric > r.Metric1) { lowestMetric = r.Metric1; } } } } if (me == null) { return(false); } foreach (IP4RouteTable ip4 in IP4RouteTable.GetCurrentTable() .Where( ip4 => ExceptionIPs.Any( ip => ip4.Destination != null && ip4.NextHop != null && ip4.Mask != null && ip4.Destination == ip.ToString() && ip4.Mask == "255.255.255.255" && ip4.NextHop != "0.0.0.0"))) { ip4.RemoveRouteRule(); } int des = 0; if (me.Metric1 >= lowestMetric) { des = (me.Metric1 - lowestMetric) + 1; } foreach (IP4RouteTable r in internetRules) { if (des > 0) { r.SetMetric1(r.Metric1 + des); } if (string.IsNullOrEmpty(r.NextHop)) { continue; } foreach (IPAddress ip in ExceptionIPs) { // if (IP4RouteTable.GetBestInterfaceIndexForIP(ip) == net.InterfaceIndex) IP4RouteTable.AddChangeRouteRule(ip, IPAddress.Parse(r.NextHop), 1, null, r.InterfaceIndex); } } FlashDnsCache(); return(true); }
// LISTENS TO VPN ADAPTER AND SENDS THE SPECIFIC PACKETS OUT THE NORMAL ADAPTER private static void TreatOUTPacketsVPNtoNormal(NdisApiDotNet outNdisapi, NetworkAdapter vpnAdapter, NetworkAdapter normalAdapter) { // Lists for re-injecting packets List <RawPacket> toAdapter = new List <RawPacket>(); List <RawPacket> toMstcp = new List <RawPacket>(); // Unmanaged memory resource for sending receiving bulk of packets // Maximum number of packets to send/receive = 64 NdisBufferResource buffer = new NdisBufferResource(64); outNdisapi.SetAdapterMode(vpnAdapter.Handle, MSTCP_FLAGS.MSTCP_FLAG_TUNNEL); outNdisapi.SetPacketEvent(vpnAdapter.Handle, outPacketEvent); do { outPacketEvent.WaitOne(); var packetList = outNdisapi.ReadPackets(vpnAdapter.Handle, buffer); while (packetList.Item1) { foreach (var packet in packetList.Item2) { Packet p = null; EthernetPacket ethernetPacket = null; TcpPacket tcpPacket = null; IPv4Packet ipv4Packet = null; ushort sport = 0; ushort dport = 0; try { p = Packet.ParsePacket(LinkLayers.Ethernet, packet.Data); ethernetPacket = (EthernetPacket)p; tcpPacket = (TcpPacket)((IPPacket)((EthernetPacket)p).PayloadPacket).PayloadPacket; ipv4Packet = (IPv4Packet)((EthernetPacket)p).PayloadPacket; sport = tcpPacket.SourcePort; dport = tcpPacket.DestinationPort; } catch (Exception ex) { if (packet.DeviceFlags == PACKET_FLAG.PACKET_FLAG_ON_RECEIVE) { toMstcp.Add(packet); } else { toAdapter.Add(packet); } Console.WriteLine($"An exeption {ex.Message} occured while trying to parse network packet. Packet will be let thru without any changes"); continue; } DumpSourceChangingFilteredPacket(packet.DeviceFlags, ipv4Packet.SourceAddress.ToString(), sport.ToString(), ipv4Packet.DestinationAddress.ToString(), dport.ToString(), p.Bytes.Length, packet.DeviceFlags == PACKET_FLAG.PACKET_FLAG_ON_RECEIVE); if (packet.DeviceFlags == PACKET_FLAG.PACKET_FLAG_ON_RECEIVE) { // Packet was received on VPN adapter, leave it as it is toMstcp.Add(packet); } else { if (ipv4Packet.SourceAddress.Equals(vpnIP)) { // Change the Source for outgoing packets that will later be sent thru normal adapter ipv4Packet.SourceAddress = localIp; ethernetPacket.SourceHardwareAddress = localMacAddress; ipv4Packet.UpdateIPChecksum(); tcpPacket.UpdateTcpChecksum(); ethernetPacket.UpdateCalculatedValues(); var newPackage = new RawPacket() { Data = p.Bytes, FilterId = packet.FilterId, Dot1q = packet.Dot1q, NdisFlags = packet.NdisFlags, DeviceFlags = packet.DeviceFlags }; toAdapter.Add(newPackage); } else { toAdapter.Add(packet); } } } if (toMstcp.Count > 0) { // If we have packets to forward upwards the network stack then do it here // RECEIVED SHOULD BE TREATED BY VPN ADAPTER outNdisapi.SendPacketsToMstcp(vpnAdapter.Handle, buffer, toMstcp); toMstcp.Clear(); } if (toAdapter.Count > 0) { // If we have packets to forward downwards the network stack then do it here // SENT SHOULD BE TREATED BY NORMAL ADAPTER outNdisapi.SendPacketsToAdapter(normalAdapter.Handle, buffer, toAdapter); toAdapter.Clear(); } packetList = outNdisapi.ReadPackets(vpnAdapter.Handle, buffer); } ; outPacketEvent.Reset(); } while (!stopCapturing); // // Release driver and associated resources // buffer.Dispose(); outNdisapi.SetPacketEvent(vpnAdapter.Handle, null); outNdisapi.SetAdapterMode(vpnAdapter.Handle, 0); }
/// <summary> /// Specific constructor for ComputationalNode class. Allows to execute node's correctly. /// </summary> /// <param name="serverIp">IPAdress of a server address name.</param> /// <param name="port">Port on which server is listening.</param> public ComputationalNode(IPAddress serverIp, int port) { if (serverIp == null || port < 0) throw new ArgumentNullException(); networkAdapter = new NetworkAdapter(serverIp, port); }
protected override void OnSetProperty(string property, Variant value) { if (property == "MTU") { uint mtu = 0; if (value.GetVariantType() == Variant.VariantType.BitStream) { var bs = (BitStream)value; bs.SeekBits(0, SeekOrigin.Begin); int len = (int)Math.Min(bs.LengthBits, 32); ulong bits = bs.ReadBits(len); mtu = LittleBitWriter.GetUInt32(bits, len); } else if (value.GetVariantType() == Variant.VariantType.ByteString) { byte[] buf = (byte[])value; int len = Math.Min(buf.Length * 8, 32); mtu = LittleBitWriter.GetUInt32(buf, len); } else { throw new SoftException("Can't set MTU, 'value' is an unsupported type."); } if (MaxMTU >= mtu && mtu >= MinMTU) { using (var cfg = NetworkAdapter.CreateInstance(_iface)) { try { cfg.MTU = mtu; } catch (Exception ex) { string msg = ex.Message; if (ex is TypeInitializationException || ex is TargetInvocationException) { msg = ex.InnerException.Message; } string err = "Failed to change MTU of '{0}' to {1}. {2}".Fmt(_iface, mtu, msg); Logger.Error(err); var se = new SoftException(err, ex); throw new SoftException(se); } _mtu = cfg.MTU; if (!_mtu.HasValue || _mtu.Value != mtu) { string err = "Failed to change MTU of '{0}' to {1}. The change did not take effect.".Fmt(_iface, mtu); Logger.Error(err); throw new SoftException(err); } else { Logger.Debug("Changed MTU of '{0}' to {1}.", _iface, mtu); } } } else { Logger.Debug("Not setting MTU of '{0}', value is out of range.", _iface); } } }
static public void GetNetworkAdress() { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); List <NetworkAdapter> adapterList = new List <NetworkAdapter>(); int i = 0; foreach (NetworkInterface adapter in nics) { //if(adapter.GetIPv4Statistics().UnicastPacketsReceived + adapter.GetIPv4Statistics().NonUnicastPacketsReceived == 0) // continue; NetworkAdapter adaptertje = new NetworkAdapter(); PhysicalAddress address = adapter.GetPhysicalAddress(); // name of the adapter adaptertje.adapterName = StringFunction.FilterString(adapter.Description); adaptertje.adapterAltName = adapter.Name; // IPv4 and IPv6 adresses and MTU if (adapter.GetIPProperties().GatewayAddresses.Count > 0) { adaptertje.gateway = adapter.GetIPProperties().GatewayAddresses[0].Address.ToString(); } foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { adaptertje.IPv4Adress = ip.Address.ToString(); adaptertje.MTU = (Mathf.Floor(adapter.GetIPProperties().GetIPv4Properties().Mtu / 100f) / 10f) + " KB"; } else if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { adaptertje.IPv6Adress = ip.Address.ToString(); adaptertje.MTU = (Mathf.Floor(adapter.GetIPProperties().GetIPv6Properties().Mtu / 100f) / 10f) + " KB"; } } // Adapter nominal speed if (adapter.Speed == 1000000000) { adaptertje.nominalSpeed = "Gigabit"; } else if (adapter.Speed > 1000000000) { adaptertje.nominalSpeed = (Mathf.Ceil((float)adapter.Speed / 100000000) / 10f) + " Gigabit"; } else if (adapter.Speed < 1000000) { adaptertje.nominalSpeed = (Mathf.Floor((float)adapter.Speed / 100f) / 10f) + " Kbps"; } else { adaptertje.nominalSpeed = (Mathf.Floor((float)adapter.Speed / 100000f) / 10f) + " Mbps"; } // MAC address byte[] bytes = address.GetAddressBytes(); string mac = null; for (i = 0; i < bytes.Length; i++) { mac = string.Concat(mac + (string.Format("{0}", bytes[i].ToString("X2")))); if (i != bytes.Length - 1) { mac = string.Concat(mac + "-"); } } adaptertje.macAdress = mac; adapterList.Add(adaptertje); } if (netAdapters.Length != adapterList.Count) { netAdapters = new NetworkAdapter[adapterList.Count]; } i = 0; foreach (NetworkAdapter adapter in adapterList) { netAdapters[i] = adapter; i++; } }
// Start is called before the first frame update void Start() { adapter = new NetworkAdapter(); adapter.Connect("tcp://127.0.0.1:7000", new TcpEnDecode(), this.NetRespEvent); }
public void Update(AdapterData adapter, List <NetworkAdapter> adapters, List <NetworkInterface> interfaces) { try { // Refresh data if (adapters == null) { adapters = NetworkAdapter.GetInstances().Cast <NetworkAdapter>().ToList(); } if (interfaces == null) { interfaces = NetworkInterface.GetAllNetworkInterfaces().ToList(); } adapter.Update(adapters, interfaces); Name = adapter.networkAdapter.Name; Mac = adapter.networkAdapter.MACAddress; Status = adapter.GetStatusText(); IsActive = adapter.networkAdapter.ConfigManagerErrorCode != NetworkAdapter.ConfigManagerErrorCodeValues.This_device_is_disabled_; HasAdapter = adapter.networkInterface != null; if (adapter.networkInterface == null) { return; } var networkInterfaceIPProperties = adapter.networkInterface.GetIPProperties(); var networkInterfaceIPv4Properties = networkInterfaceIPProperties.GetIPv4Properties(); if (adapter.networkAdapter.NetConnectionStatus == 2) { Speed = (adapter.networkAdapter.Speed / (1000 * 1000)).ToString("F1") + " Mbps"; } else { Speed = null; } IsDhcpEnabled = networkInterfaceIPv4Properties.IsDhcpEnabled; WinsEnabled = networkInterfaceIPv4Properties.UsesWins.ToActiveText(); // Ignore loop-back addresses & IPv6 var tempIp = string.Empty; foreach (var item in networkInterfaceIPProperties.UnicastAddresses .Where(z => z.Address.AddressFamily == AddressFamily.InterNetwork) .Where(z => !IPAddress.IsLoopback(z.Address)) .Where(z => z.IPv4Mask != null && z.Address != null)) { tempIp += string.Format(@"{0}\{1}{2}", item.Address, item.IPv4Mask, Environment.NewLine); } Ip = tempIp.Trim(); var tempDnsServers = string.Empty; foreach (var item in networkInterfaceIPProperties.DnsAddresses.Where(z => z.AddressFamily == AddressFamily.InterNetwork)) { tempDnsServers += item + Environment.NewLine; } DnsServers = tempDnsServers.Trim(); var tempGateways = string.Empty; foreach (var item in networkInterfaceIPProperties.GatewayAddresses) { tempGateways += item.Address + Environment.NewLine; } Gateways = tempGateways.Trim(); var TempDhcpServers = string.Empty; foreach (var item in networkInterfaceIPProperties.DhcpServerAddresses.Where(z => z.AddressFamily == AddressFamily.InterNetwork)) { TempDhcpServers += item + Environment.NewLine; } DhcpServers = TempDhcpServers.Trim(); var tempWinsServers = string.Empty; foreach (var item in networkInterfaceIPProperties.WinsServersAddresses.Where(z => z.AddressFamily == AddressFamily.InterNetwork)) { tempWinsServers += item + Environment.NewLine; } WinsServers = tempWinsServers.Trim(); var tempAnyCast = string.Empty; foreach (var item in networkInterfaceIPProperties.AnycastAddresses.Where(z => z.Address.AddressFamily == AddressFamily.InterNetwork)) { tempAnyCast += item.Address + Environment.NewLine; } AnyCast = tempAnyCast.Trim(); var tempMulticast = string.Empty; foreach (var item in networkInterfaceIPProperties.MulticastAddresses.Where(z => z.Address.AddressFamily == AddressFamily.InterNetwork)) { tempMulticast += item.Address + Environment.NewLine; } Multicast = tempMulticast.Trim(); } catch (Exception ex) { SimpleMessenger.Default.SendMessage("ErrorText", ex.Message); } }
// how to call: // ForceBindIP.exe 192.168.2.32 "C:\Program Files\Mozilla Firefox\firefox.exe" // public Error StartAndSetApplication(NetworkAdapter adapter, Application app) { return(StartAndSetApplication(app.Path, adapter.Ip, app.IsCompatibility)); }
public void ModifyMacAddress_ByConnectionIDTest() { //78:45:C4:AC:26:81 NetworkAdapter.ModifyMacAddress(1, ""); }
static void Main(string[] args) { int ordered = 0; int brief = 0; int netOnly = 0; int hdOnly = 0; if (args.Length == 0) { Console.WriteLine("arguments:\n\t" + "-o #: get assigned instance\n\t" + "-b: brief\n\t-n: network adapter only\n\t" + "-d: disk only\n\t-a: all\n\t" + "-h: this usage\n"); } else { foreach (String arg in args) { switch (arg) { case "-o": ordered = 1; break; case "-b": brief = 1; break; case "-n": netOnly = 1; hdOnly = 0; break; case "-d": hdOnly = 1; netOnly = 0; break; case "-a": hdOnly = 0; netOnly = 0; ordered = 0; break; case "-h": Console.WriteLine("arguments:\n\t" + "-o #: get assigned instance\n\t" + "-b: brief\n\t-n: network adapter only\n\t" + "-d: disk only\n\t-a: all\n\t" + "-h: this usage\n"); Environment.Exit(0); break; default: if (ordered > 0 && !Int32.TryParse(arg, out ordered)) { ordered = 0; } break; } } } //BIOS biosOB; //OS osOB; //Serial[] serial; NetworkAdapter[] networkAdapterOB; LogicalDisk[] hdOB; //biosOB = WMIHelper.WMIHelper.FillBiosInformation(Environment.MachineName, "", "", "Win32_BIOS"); //osOB = WMIHelper.WMIHelper.FillOSInformation(Environment.MachineName, "", "", "Win32_OperatingSystem"); networkAdapterOB = WMIHelper.WMIHelper.FillNetworkAdapter(Environment.MachineName, "", "", "Win32_NetworkAdapterConfiguration"); hdOB = WMIHelper.WMIHelper.FillLogicalDisks(Environment.MachineName, "", "", "Win32_LogicalDIsk"); //serial = WMIHelper.WMIHelper.FillSerial(Environment.MachineName, "", "", "Win32_PnPEntity", "CP210x"); //for (int i = 0; i < serial.Count(); ++i) // Console.WriteLine("{0}: {1}", serial[i].port, serial[i].Description); //Console.WriteLine("BIOS # {0}", biosOB.SerialNumber); //Console.WriteLine("OS # {0}", osOB.SerialNumber); if (hdOnly == 0) { for (int i = 0; i < networkAdapterOB.Count(); ++i) { NetworkAdapter na = networkAdapterOB[i]; if (na.MACAddress.Length > 0) { if (ordered > 1) { ordered--; } else { if (brief == 1) { Console.WriteLine("{0}", na.MACAddress); } else { Console.WriteLine("{0} # Network Interface({1})", na.MACAddress, na.Description); } if (ordered == 1) { netOnly = 1; break; } } } } } if (netOnly == 0) { for (int i = 0; i < hdOB.Count(); ++i) { LogicalDisk ld = hdOB[i]; if (ld.VolumeSerialNumber.Length > 0) { if (ordered > 1) { ordered--; } else { if (brief == 1) { Console.WriteLine("{0}", ld.VolumeSerialNumber); } else { Console.WriteLine("{0} # Harddisk({1})", ld.VolumeSerialNumber, ld.Name); } if (ordered == 1) { netOnly = 1; break; } } } } } }
public Pathfinder(NetworkAdapter network) { this.network = network; this.CreateNodeVisitContainer = () => new NodeVisitArray(network.MaxId()); }
public int Remove(NetworkAdapter model) { _myDbContext.NetworkAdapters.Remove(model); return(_myDbContext.SaveChanges()); }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> public async void StartListener() { // Overriding the listener here is safe as it will be deleted once all references to it are gone. // However, in many cases this is a dangerous pattern to override data semi-randomly (each time user // clicked the button) so we block it here. if (CoreApplication.Properties.ContainsKey("listener")) { Util.Log( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(PortOrServicenameForListener)) { Util.Log("Please provide a service name.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); LocalHostItem selectedLocalHost = null; if ((BindToAddress_IsChecked == true) || (BindToAdapter_IsChecked == true)) { selectedLocalHost = new LocalHostItem(RemoteSocketListenerSvrName); if (selectedLocalHost == null) { Util.Log("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // If necessary, tweak the listener's control options before carrying out the bind operation. // These options will be automatically applied to the connected StreamSockets resulting from // incoming connections (i.e., those passed as arguments to the ConnectionReceived event handler). // Refer to the StreamSocketListenerControl class' MSDN documentation for the full list of control options. listener.Control.KeepAlive = false; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny_IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(PortOrServicenameForListener); Util.Log("Listening", NotifyType.StatusMessage); } else if (BindToAddress_IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, PortOrServicenameForListener); Util.Log( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); Util.Log( "On Port " + PortOrServicenameForListener, NotifyType.StatusMessage); } else if (BindToAdapter_IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overridden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; // For demo purposes, ensure that we use the same adapter in the client connect scenario. CoreApplication.Properties.Add("adapter", selectedAdapter); await listener.BindServiceNameAsync( PortOrServicenameForListener, SocketProtectionLevel.PlainSocket, selectedAdapter); Util.Log( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } Util.Log( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public static void Main(string[] aArgs) { Console.WriteLine("TestPerformanceCpCs - starting"); InitParams initParams = new InitParams(); using (Library lib = Library.Create(initParams)) { SubnetList subnetList = new SubnetList(); NetworkAdapter nif = subnetList.SubnetAt(0); uint subnet = nif.Subnet(); subnetList.Dispose(); var deviceListFactory = new CpUpnpDeviceListFactory(lib.StartCp(subnet)); CpDevice device = null; Semaphore sem = new Semaphore(0, 1); var deviceList = deviceListFactory.CreateListServiceType("openhome.org", "TestBasic", 1, (aDeviceList, aDevice) => { if (device != null) { throw new Exception("Found more than one device. Giving up as test results will probably be invalid."); } device = aDevice; device.AddRef(); sem.Release(); }, (aDeviceList, aDevice) => { throw new Exception("ERROR: Device removed while test is running."); }); sem.WaitOne(); // actions Console.WriteLine(""); int[] threadCounts = { 1, 2, 4 }; foreach (int threadCount in threadCounts) { List <Thread> threads = new List <Thread>(); for (int i = 0; i < threadCount; i++) { threads.Add(new Thread(ActionThread)); } ThreadArgs threadArgs = new ThreadArgs(device, kTestDurationMs); for (int i = 0; i < threadCount; i++) { threads[i].Start(threadArgs); } for (int i = 0; i < threadCount; i++) { threads[i].Join(); } Console.WriteLine("Invoked {0} actions in {1}ms using {2} threads", threadArgs.Count, kTestDurationMs, threadCount); } // subscriptions Thread thread = new Thread(SubscriptionThread); ThreadArgs args = new ThreadArgs(device, kTestDurationMs); thread.Start(args); thread.Join(); Console.WriteLine("\nCompleted {0} subscriptions in {1}ms\n", args.Count, kTestDurationMs); device.RemoveRef(); deviceList.Dispose(); Console.WriteLine("\nTests complete. Press 'q' to exit."); while (Console.ReadKey(true).KeyChar != 'q') { ; } } }
public ModuleConfiguration(NetworkAdapter na) { this.na = na; moduleOrder = na.modules.GetModuleOrder(); InitializeComponent(); }
void MoveFromDisabledToEnabled(NetworkAdapter item) { NetworkAdaptersDisabled.Remove(item); NetworkAdaptersEnabled.Add(item); UpdateAdaptersList(); }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { // Overriding the listener here is safe as it will be deleted once all references to it are gone. // However, in many cases this is a dangerous pattern to override data semi-randomly (each time user // clicked the button) so we block it here. if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); CoreApplication.Properties.Remove("adapter"); LocalHostItem selectedLocalHost = null; if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny.IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overriden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; // For demo purposes, ensure that use the same adapter in the client connect scenario. CoreApplication.Properties.Add("adapter", selectedAdapter); await listener.BindServiceNameAsync( ServiceNameForListener.Text, SocketProtectionLevel.PlainSocket, selectedAdapter); rootPage.NotifyUser( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
private void UpdateDynamicSystemData() { DynamicSystemData = new DynamicSystemInfo(); try { MEMORYSTATUSEX memoryStatus = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memoryStatus); DynamicSystemData.PhysicalMemory = $"total = {memoryStatus.ullTotalPhys / GB:N2} GB, available = {memoryStatus.ullAvailPhys / GB:N2} GB"; DynamicSystemData.PhysicalPlusPagefile = $"total = {memoryStatus.ullTotalPageFile / GB:N2} GB, available = {memoryStatus.ullAvailPageFile / GB:N2} GB"; DynamicSystemData.VirtualMemory = $"total = {memoryStatus.ullTotalVirtual / GB:N2} GB, available = {memoryStatus.ullAvailVirtual / GB:N2} GB"; ulong pageFileOnDisk = memoryStatus.ullTotalPageFile - memoryStatus.ullTotalPhys; DynamicSystemData.PagefileOnDisk = $"{pageFileOnDisk / GB:N2} GB"; DynamicSystemData.MemoryLoad = $"{memoryStatus.dwMemoryLoad}%"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "MEMORYSTATUSEX", ex.Message); } bool isBatteryAvailable = true; try { SYSTEM_POWER_STATUS powerStatus = new SYSTEM_POWER_STATUS(); GetSystemPowerStatus(ref powerStatus); DynamicSystemData.ACLineStatus = powerStatus.ACLineStatus.ToString(); DynamicSystemData.BatteryChargeStatus = $"{powerStatus.BatteryChargeStatus:G}"; if (powerStatus.BatteryChargeStatus == BatteryFlag.NoSystemBattery || powerStatus.BatteryChargeStatus == BatteryFlag.Unknown) { isBatteryAvailable = false; DynamicSystemData.BatteryLife = "n/a"; } else { DynamicSystemData.BatteryLife = $"{powerStatus.BatteryLifePercent}%"; } DynamicSystemData.BatterySaver = powerStatus.BatterySaver.ToString(); } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "SYSTEM_POWER_STATUS", ex.Message); } if (isBatteryAvailable) { try { Battery battery = Battery.AggregateBattery; BatteryReport batteryReport = battery.GetReport(); DynamicSystemData.ChargeRate = $"{batteryReport.ChargeRateInMilliwatts:N0} mW"; DynamicSystemData.Capacity = $"design = {batteryReport.DesignCapacityInMilliwattHours:N0} mWh, " + $"full = {batteryReport.FullChargeCapacityInMilliwattHours:N0} mWh, " + $"remaining = {batteryReport.RemainingCapacityInMilliwattHours:N0} mWh"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "BatteryReport", ex.Message); } } else { DynamicSystemData.ChargeRate = "n/a"; DynamicSystemData.Capacity = "n/a"; } try { ulong freeBytesAvailable; ulong totalNumberOfBytes; ulong totalNumberOfFreeBytes; // You can only specify a folder path that this app can access, but you can // get full disk information from any folder path. IStorageFolder appFolder = ApplicationData.Current.LocalFolder; GetDiskFreeSpaceEx(appFolder.Path, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); DynamicSystemData.TotalDiskSize = $"{totalNumberOfBytes / GB:N2} GB"; DynamicSystemData.DiskFreeSpace = $"{freeBytesAvailable / GB:N2} GB"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetDiskFreeSpaceEx", ex.Message); } try { IntPtr infoPtr = IntPtr.Zero; uint infoLen = (uint)Marshal.SizeOf <FIXED_INFO>(); int ret = -1; while (ret != ERROR_SUCCESS) { infoPtr = Marshal.AllocHGlobal(Convert.ToInt32(infoLen)); ret = GetNetworkParams(infoPtr, ref infoLen); if (ret == ERROR_BUFFER_OVERFLOW) { // Try again with a bigger buffer. Marshal.FreeHGlobal(infoPtr); continue; } } FIXED_INFO info = Marshal.PtrToStructure <FIXED_INFO>(infoPtr); DynamicSystemData.DomainName = info.DomainName; string nodeType = string.Empty; switch (info.NodeType) { case BROADCAST_NODETYPE: nodeType = "Broadcast"; break; case PEER_TO_PEER_NODETYPE: nodeType = "Peer to Peer"; break; case MIXED_NODETYPE: nodeType = "Mixed"; break; case HYBRID_NODETYPE: nodeType = "Hybrid"; break; default: nodeType = $"Unknown ({info.NodeType})"; break; } DynamicSystemData.NodeType = nodeType; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetNetworkParams", ex.Message); } try { ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile(); DynamicSystemData.ConnectedProfile = profile.ProfileName; NetworkAdapter internetAdapter = profile.NetworkAdapter; DynamicSystemData.IanaInterfaceType = $"{(IanaInterfaceType)internetAdapter.IanaInterfaceType}"; DynamicSystemData.InboundSpeed = $"{internetAdapter.InboundMaxBitsPerSecond / MBPS:N0} Mbps"; DynamicSystemData.OutboundSpeed = $"{internetAdapter.OutboundMaxBitsPerSecond / MBPS:N0} Mbps"; IReadOnlyList <HostName> hostNames = NetworkInformation.GetHostNames(); HostName connectedHost = hostNames.Where (h => h.IPInformation != null && h.IPInformation.NetworkAdapter != null && h.IPInformation.NetworkAdapter.NetworkAdapterId == internetAdapter.NetworkAdapterId) .FirstOrDefault(); if (connectedHost != null) { DynamicSystemData.HostAddress = connectedHost.CanonicalName; DynamicSystemData.AddressType = connectedHost.Type.ToString(); } } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetInternetConnectionProfile", ex.Message); } dynamicDataGrid.DataContext = DynamicSystemData; }