/// <summary> /// Returns the index for the interface which has the ip address assigned /// </summary> /// <param name="ipAddress"> The ip address to look for </param> /// <returns> The index for the interface which has the ip address assigned </returns> public static int GetInterfaceIndex(this IPAddress ipAddress) { if (ipAddress == null) { throw new ArgumentNullException("ipAddress"); } IPInterfaceProperties interfaceProperty = NetworkInterface.GetAllNetworkInterfaces() .Select(n => n.GetIPProperties()) .FirstOrDefault(p => p.UnicastAddresses.Any(a => a.Address.Equals(ipAddress))); if (interfaceProperty != null) { if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { IPv4InterfaceProperties property = interfaceProperty.GetIPv4Properties(); if (property != null) { return(property.Index); } } else { IPv6InterfaceProperties property = interfaceProperty.GetIPv6Properties(); if (property != null) { return(property.Index); } } } throw new ArgumentOutOfRangeException("ipAddress", "The given ip address is not configured on the local system"); }
private static NetworkInterface GetInterface(int index) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { try { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties ip4 = adapterProperties.GetIPv4Properties(); if ((ip4 != null) && (ip4.Index == index)) { return(adapter); } IPv6InterfaceProperties ip6 = adapterProperties.GetIPv6Properties(); if ((ip6 != null) && (ip6.Index == index)) { return(adapter); } } catch (NetworkInformationException e) { if (e.NativeErrorCode != (int)System.Net.Sockets.SocketError.ProtocolNotSupported) { throw; } } } return(null); }
[PlatformSpecific(PlatformID.Windows)] // Linux and OSX do not support some of these public void IPInfoTest_AccessAllIPv4Properties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv4 Properties:"); if (!nic.Supports(NetworkInterfaceComponent.IPv4)) { var nie = Assert.Throws <NetworkInformationException>(() => ipProperties.GetIPv4Properties()); Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode); continue; } IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); _log.WriteLine("Index: " + ipv4Properties.Index); _log.WriteLine("IsAutomaticPrivateAddressingActive: " + ipv4Properties.IsAutomaticPrivateAddressingActive); _log.WriteLine("IsAutomaticPrivateAddressingEnabled: " + ipv4Properties.IsAutomaticPrivateAddressingEnabled); _log.WriteLine("IsDhcpEnabled: " + ipv4Properties.IsDhcpEnabled); _log.WriteLine("IsForwardingEnabled: " + ipv4Properties.IsForwardingEnabled); _log.WriteLine("Mtu: " + ipv4Properties.Mtu); _log.WriteLine("UsesWins: " + ipv4Properties.UsesWins); } }
public static int GetAdapterId(string adapterId) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); Console.WriteLine("IPv4 interface information for {0}.{1}", properties.HostName, properties.DomainName); int id = 0; foreach (NetworkInterface adapter in nics) { //Console.WriteLine(adapter.Description); //Console.WriteLine(adapter.Name); if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false) { continue; } if (!adapter.Id.Equals(adapterId, StringComparison.OrdinalIgnoreCase)) { continue; } IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); if (p == null) { Console.WriteLine("No information is available for this interface."); continue; } id = adapter.GetIPProperties().GetIPv4Properties().Index; } return(id); }
/// <summary> /// /// </summary> /// <param name="connName"></param> /// <returns></returns> public static string getCurrentIP(string connName) { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { if (connName == adapter.Name) { IPInterfaceProperties ipProps = adapter.GetIPProperties(); IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties(); if (ipv4Props.IsDhcpEnabled) { return(DHCP); } else { foreach (UnicastIPAddressInformation ipInfo in ipProps.UnicastAddresses) { if (ipInfo.Address.AddressFamily == AddressFamily.InterNetwork) { return(ipInfo.Address.ToString()); } } } } } return(null); }
public static IList <IPAddress> GetAllIPAddress() { List <IPAddress> result = new List <IPAddress>(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties ip_properties = adapter.GetIPProperties(); if (!adapter.GetIPProperties().MulticastAddresses.Any()) { continue; // most of VPN adapters will be skipped } if (!adapter.SupportsMulticast) { continue; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != adapter.OperationalStatus) { continue; // this adapter is off or not connected } IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) { continue; // IPv4 is not configured on this adapter } } return(result); }
public void Send() { UpdateWatch(); UdpClient tmpClient = new UdpClient(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.Name == "wlan0") { IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties(); tmpClient.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)IPAddress.HostToNetworkOrder(p.Index)); //Console.WriteLine ("assigned " + adapter.Name + " as multicast address : " + (int)IPAddress.HostToNetworkOrder(p.Index)); } } IPAddress multicastaddress = IPAddress.Parse(MULTICAST_IP); tmpClient.JoinMulticastGroup(multicastaddress); IPEndPoint multicastPoint = new IPEndPoint(multicastaddress, PORT_NUMBER); // Can send on broadcast // Yep, you can serialize a whole list ! string json = new JsonService().Serialize(watches_); byte[] buffer = Encoding.ASCII.GetBytes(json); tmpClient.Send(buffer, buffer.Length, multicastPoint); tmpClient.Close(); }
static Dictionary <int, string> PrintInterfaceIndex() { Dictionary <int, string> adapterNames = new Dictionary <int, string>(); try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); if (p == null) { continue; } if (!adapterNames.ContainsKey(p.Index)) { adapterNames.Add(p.Index, adapter.Name); } } } catch (Exception) { } return(adapterNames); }
public static byte[] GetLocalKey() { NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); int num = -1; int index = -1; int num4 = allNetworkInterfaces.Length - 1; for (int i = 0; i <= num4; i++) { switch (allNetworkInterfaces[i].OperationalStatus) { case OperationalStatus.Up: { IPInterfaceProperties iPProperties = allNetworkInterfaces[i].GetIPProperties(); if (iPProperties == null) { continue; } IPv4InterfaceProperties properties2 = iPProperties.GetIPv4Properties(); if ((properties2 == null) || ((index >= 0) && (properties2.Index >= index))) { continue; } num = i; index = properties2.Index; } break; } } byte[] buffer2 = ConvertByteEncoding(Mac(GetMACAddress())); return(num >= 0 ? buffer2 : Encoding.Default.GetBytes(Environment.UserName + CultureInfo.CurrentCulture.TwoLetterISOLanguageName)); }
private static bool IsNicGoodForMulticast(NetworkInterface adapter) { IPInterfaceProperties ip_properties = adapter.GetIPProperties(); if (!adapter.GetIPProperties().MulticastAddresses.Any()) { return(false); // most of VPN adapters will be skipped } if (!adapter.SupportsMulticast) { return(false); // Doesn't support Multicast, no point in trying } if (OperationalStatus.Up != adapter.OperationalStatus) { return(false); // This adapter is off or not connected } IPv4InterfaceProperties IPv4Props = adapter.GetIPProperties().GetIPv4Properties(); if (IPv4Props == null) { return(false); // IPv4 is not configured on this adapter } // IPv4InterfaceProperties.Index's getter can throw if the interface has no index try { _ = IPv4Props.Index; } catch { return(false); } return(true); }
private static List <Socket> InitSockets() { List <Socket> multicastSockets = new List <Socket>(); NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface netiface in allNetworkInterfaces) { if (netiface.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties properties2 = netiface.GetIPProperties().GetIPv4Properties(); if (properties2 != null) { foreach (int num in PLAYER_MULTICAST_PORTS) { Socket item = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { item.ExclusiveAddressUse = false; } catch (SocketException) { } item.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint localEP = new IPEndPoint(IPAddress.Any, num); item.Bind(localEP); IPAddress group = IPAddress.Parse(PLAYER_MULTICAST_GROUP); item.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(group, properties2.Index)); multicastSockets.Add(item); } } } } return(multicastSockets); }
public int getMTU() { var adapter = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == this.deviceName).First(); IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); return(p.Mtu); }
public static bool IS_DHCP()//是否开启DHCP { NetworkInterface[] adapter = NetworkInterface.GetAllNetworkInterfaces(); IPInterfaceProperties ipp = adapter[0].GetIPProperties(); IPv4InterfaceProperties ip4ip = ipp.GetIPv4Properties(); return(ip4ip.IsDhcpEnabled); }
public void RefreshInfos() { listAdapter.Clear(); adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { var ipProp = adapter.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipProp.UnicastAddresses) { if ((adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) && ip.Address.AddressFamily == AddressFamily.InterNetwork) // { IPInterfaceProperties adapterProp = adapter.GetIPProperties(); IPv4InterfaceProperties adapterPropV4 = adapterProp.GetIPv4Properties(); GatewayIPAddressInformationCollection gate = adapter.GetIPProperties().GatewayAddresses; listAdapter.Add(new AdapterObject { Name = adapter.Name, Description = adapter.Description, NetworkInterfaceType = adapter.NetworkInterfaceType.ToString(), PhysicalAddress = adapter.GetPhysicalAddress().ToString(), IsReceiveOnly = adapter.IsReceiveOnly, SupportMulticast = adapter.SupportsMulticast, IsOperationalStatusUp = adapter.OperationalStatus == OperationalStatus.Up, Speed = adapter.Speed, IpAddress = ip.Address.ToString(), SubnetMask = ip.IPv4Mask.ToString(), Gateway = gate.Any() ? gate.FirstOrDefault().Address.ToString() : "", DnsSuffix = adapterProp.DnsSuffix, IsDnsEnabled = adapterProp.IsDnsEnabled, IsDynamicDnsEnabled = adapterProp.IsDynamicDnsEnabled, Index = adapterPropV4.Index, Mtu = adapterPropV4.Mtu, IsAutomaticPrivateAddressingActive = adapterPropV4.IsAutomaticPrivateAddressingActive, IsAutomaticPrivateAddressingEnabled = adapterPropV4.IsAutomaticPrivateAddressingEnabled, IsForwardingEnabled = adapterPropV4.IsForwardingEnabled, UsesWins = adapterPropV4.UsesWins, IsDHCPEnabled = adapterPropV4.IsDhcpEnabled, DHCPServer = adapterProp.DhcpServerAddresses.FirstOrDefault() != null ? adapterProp.DhcpServerAddresses.FirstOrDefault().ToString() : "", DNSServer1 = (adapterProp.DnsAddresses.Count > 0 && adapterProp.DnsAddresses[0].AddressFamily == AddressFamily.InterNetwork) ? adapterProp.DnsAddresses[0]?.ToString() : "", DNSServer2 = (adapterProp.DnsAddresses.Count > 1 && adapterProp.DnsAddresses[1].AddressFamily == AddressFamily.InterNetwork) ? adapterProp.DnsAddresses[1]?.ToString() : "", Internet = adapter.GetIPv4Statistics().BytesReceived > 0 && adapter.GetIPv4Statistics().BytesSent > 0 }); } } } }
/// <summary> /// Initializes new instance of <see cref="IPv4InterfacePropertiesAdapter"/>. /// </summary> /// <param name="props">Properties to be used by the adapter.</param> public IPv4InterfacePropertiesAdapter(IPv4InterfaceProperties props) : base(props) { if (props == null) { throw new ArgumentNullException(nameof(props)); } _props = props; }
public static NetworkAdaptor GetNetworkAdaptor(int interfaceIndex) { NetworkAdaptor na = null; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); if (!HasIp4Support(adapter)) { continue; } IPv4InterfaceProperties ip4Properties = properties.GetIPv4Properties(); if (properties.GetIPv4Properties().Index == interfaceIndex) { na = new NetworkAdaptor(); na.Name = adapter.Name; na.Description = adapter.Description; na.MACAddress = adapter.GetPhysicalAddress().ToString(); na.InterfaceIndex = ip4Properties.Index; na.PrimaryIpAddress = properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork)?.First()?.Address; na.SubnetMask = properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork)?.First()?.IPv4Mask; if (properties.GatewayAddresses.Count > 0) { na.PrimaryGateway = null; foreach (GatewayIPAddressInformation gatewayInfo in properties.GatewayAddresses) { if (gatewayInfo.Address != null && gatewayInfo.Address.AddressFamily == AddressFamily.InterNetwork) { na.PrimaryGateway = gatewayInfo.Address; break; } } } else { //if the gateways on the Network adaptor properties is null, then get it from the routing table, especially the case for VPN routers List <Ip4RouteEntry> routeTable = Ip4RouteTable.GetRouteTable(); if (routeTable.Where(i => i.InterfaceIndex == na.InterfaceIndex)?.Count() > 0) { na.PrimaryGateway = routeTable.Where(i => i.InterfaceIndex == na.InterfaceIndex)?.First()?.GatewayIP; } } //not ideal and incorrect, but hopefully it doesn't execute this as the gateways are defined elsewhere //the correct way is to locate the primary gateway in some other property other than the 3 methods here if (na.PrimaryGateway == null && properties.DhcpServerAddresses.Count > 0) { na.PrimaryGateway = properties.DhcpServerAddresses.First(); } break; } } return(na); }
public static List <NetworkAdaptor> GetAllNetworkAdaptor() { List <NetworkAdaptor> naList = new List <NetworkAdaptor>(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); IPv4InterfaceProperties ip4Properties = null; if (!HasIp4Support(adapter)) { continue; } else { ip4Properties = properties.GetIPv4Properties(); } NetworkAdaptor na = new NetworkAdaptor(); na.Name = adapter.Name; na.Description = adapter.Description; na.MACAddress = adapter.GetPhysicalAddress().ToString(); na.InterfaceIndex = ip4Properties != null ? ip4Properties.Index : 0; na.PrimaryIpAddress = properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork)?.First()?.Address; na.SubnetMask = properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork)?.First()?.IPv4Mask; if (properties.GatewayAddresses.Count > 0) { na.PrimaryGateway = null; foreach (GatewayIPAddressInformation gatewayInfo in properties.GatewayAddresses) { if (gatewayInfo.Address != null && gatewayInfo.Address.AddressFamily == AddressFamily.InterNetwork) { na.PrimaryGateway = gatewayInfo.Address; break; } } } else { //if the gateways on the Network adaptor properties is null, then get it from the routing table List <Ip4RouteEntry> routeTable = Ip4RouteTable.GetRouteTable(); if (routeTable.Where(i => i.InterfaceIndex == na.InterfaceIndex).Count() > 0) { na.PrimaryGateway = routeTable.Where(i => i.InterfaceIndex == na.InterfaceIndex)?.First()?.GatewayIP; } } if (na.PrimaryGateway == null && properties.DhcpServerAddresses.Count > 0) { na.PrimaryGateway = properties.DhcpServerAddresses.First(); } naList.Add(na); } return(naList); }
public static IPConfig IPv4NetworkInterfaces(string nameInterface) { NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface Interface in Interfaces) { if (Interface.Name != nameInterface) { continue; } if (Interface.OperationalStatus != OperationalStatus.Up) { continue; } if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } IPInterfaceProperties adapterProperties = Interface.GetIPProperties(); Console.WriteLine(Interface.Name); foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { continue; } _ipConfig = new IPConfig(); IPv4InterfaceProperties ipProperties = adapterProperties.GetIPv4Properties(); IPAddressCollection dnsServers = adapterProperties.DnsAddresses; var defaultGateway = adapterProperties.GatewayAddresses.Select(i => i?.Address).Where(x => x != null).FirstOrDefault(); _ipConfig.IsDhcpEnabled = ipProperties.IsDhcpEnabled; _ipConfig.IsDnsEnabled = DNSAutoOrStatic(Interface.Id); _ipConfig.IpAddress = ConvertHelper.CnvNullToString(ip.Address); _ipConfig.Subnet = ConvertHelper.CnvNullToString(ip.IPv4Mask); _ipConfig.Gateway = ConvertHelper.CnvNullToString(defaultGateway); if (dnsServers.Count > 0) { _ipConfig.DNS = ConvertHelper.CnvNullToString(dnsServers[0]); } _ipConfig.NICName = Interface.Description; _NICName = _ipConfig.NICName; } } return(_ipConfig); }
public static void Launch() { if (NetworkInterface.GetIsNetworkAvailable()) { NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in networkInterfaces) { PhysicalAddress physicalAddress = networkInterface.GetPhysicalAddress(); // Add : each two numbers string physicalAddressString = Regex.Replace(physicalAddress.ToString(), ".{2}", "$0:"); // Remove trailing ":"; from 20:10:BB: to 20:10:BB if (physicalAddressString.Length > 0) { physicalAddressString = physicalAddressString.Substring(0, physicalAddressString.Length - 1); } Console.WriteLine(networkInterface.Name); Console.WriteLine("\tPhysical Address: {0}", physicalAddressString); Console.WriteLine("\tOperational Status: {0}", networkInterface.OperationalStatus); IPInterfaceProperties ipProperties = networkInterface.GetIPProperties(); IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); UnicastIPAddressInformationCollection unicastAddresses = ipProperties.UnicastAddresses; foreach (UnicastIPAddressInformation unicastAddress in unicastAddresses) { Console.WriteLine("\tUnicast Address: {0}", unicastAddress.Address); Console.WriteLine("\tMask: {0}", unicastAddress.IPv4Mask); } IPAddressCollection dhcServerAddresses = ipProperties.DhcpServerAddresses; foreach (IPAddress dhcServerAddress in dhcServerAddresses) { Console.WriteLine("\tDHCP Server Address: {0}", dhcServerAddress); } Console.WriteLine("\tIndex: {0}\n\tIsDhcpEnabled: {1}", ipv4Properties.Index, ipv4Properties.IsDhcpEnabled); Console.Out.Flush(); } } else { Console.WriteLine("No network interfaces available on your System."); } }
public void ListAllNetworkInterfaces() { this.Items.Clear();//Clean all first! NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in networkInterfaces) { if (OperationalStatus.Up != adapter.OperationalStatus) { //Skip disconnected network. continue; } if (NetworkInterfaceType.Loopback == adapter.NetworkInterfaceType) { //We don't want the loopack interface. continue; } //Get network with IPV4. IPInterfaceProperties ipProperties = adapter.GetIPProperties(); IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); if (null != ipv4Properties) { //foreach( ipProperties.UnicastAddresses.Count foreach (UnicastIPAddressInformation unicastIpAddress in ipProperties.UnicastAddresses) { if (unicastIpAddress.Address.IsIPv6LinkLocal | unicastIpAddress.Address.IsIPv6Multicast | unicastIpAddress.Address.IsIPv6SiteLocal | unicastIpAddress.Address.IsIPv6Teredo) { //Sorry. We don't support IPV6 currently. } else { KeyValuePair <IPAddress, int> networkIndexIpPair = new KeyValuePair <IPAddress, int>(unicastIpAddress.Address, ipv4Properties.Index); this.Items.Add(networkIndexIpPair); } } } } //Select the first one by default. if (this.Items.Count != 0) { this.SelectedIndex = 0; } }
string getIpv4AddrString(NetworkInterface nic) { if (nic.Supports(NetworkInterfaceComponent.IPv4)) { IPInterfaceProperties ipprop = nic.GetIPProperties(); IPv4InterfaceProperties ipv4prop = ipprop.GetIPv4Properties(); foreach (UnicastIPAddressInformation addr in ipprop.UnicastAddresses) { if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { return(addr.Address.ToString()); } } } return(null); }
public bool IsPublicConnected() { if ((publicConn != null) && publicConn.IsConnected) { return(true); } if (publicStrGuid.Equals(autoPublicConnection)) { NetworkInterface nicInet = null; foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { IPv4InterfaceProperties ip4Props = nic.GetIPProperties().GetIPv4Properties(); if ((nic.GetIPProperties().GatewayAddresses.Count > 0) && (ip4Props != null) && (nic.OperationalStatus == OperationalStatus.Up)) { if (nicInet == null) { nicInet = nic; } else if (ip4Props.Index < nicInet.GetIPProperties().GetIPv4Properties().Index) { nicInet = nic; } } } if (nicInet != null) { lock (connectionsLock) { publicConn = (from c in Connections where !c.IsMatch(privateStrGUID) && c.IsMatch(nicInet.Id) select c).FirstOrDefault(); if (publicConn != null) { Trace.TraceInformation("ICS: Detected internet connection {0}", nicInet.Name); } } } else { Trace.TraceInformation("ICS: Unable to lookup internet connection"); } } return((publicConn != null) && publicConn.IsConnected); }
public PlayerConnection() { m_MulticastSockets = new List <Socket>(); var nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false) { continue; } //Fetching adapter index IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); foreach (var port in PLAYER_MULTICAST_PORTS) { var multicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { multicastSocket.ExclusiveAddressUse = false; } catch (SocketException) { // This option is not supported on some OSs } multicastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); var ipep = new IPEndPoint(IPAddress.Any, port); multicastSocket.Bind(ipep); var ip = IPAddress.Parse(PLAYER_MULTICAST_GROUP); try { multicastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, p.Index)); Log.Info($"Setting up multicast option: {ip}: {port}"); } catch (SocketException e) { Log.Error($"Failed to set socket options on adapter {adapter.Id}, address {ip}: {port}", e); } m_MulticastSockets.Add(multicastSocket); } } }
public static void DisplayIPv4NetworkInterfaces() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); Console.WriteLine("IPv4 interface information for {0}.{1}", properties.HostName, properties.DomainName); Console.WriteLine(); foreach (NetworkInterface adapter in nics) { // Only display informatin for interfaces that support IPv4. if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false) { continue; } Console.WriteLine(adapter.Description); // Underline the description. Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '=')); IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); // Try to get the IPv4 interface properties. IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); if (p == null) { Console.WriteLine("No IPv4 information is available for this interface."); Console.WriteLine(); continue; } // Display the IPv4 specific data. 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); Console.WriteLine(" DHPC enable ......................... : {0}", p.IsDhcpEnabled); Console.WriteLine(); } }
private void Init(bool sendBroadcast = false) { if (sendBroadcast) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties ipprops = adapter.GetIPProperties(); if (ipprops.MulticastAddresses.Count == 0 || // most of VPN adapters will be skipped !adapter.SupportsMulticast || // multicast is meaningless for this type of connection OperationalStatus.Up != adapter.OperationalStatus) // this adapter is off or not connected { continue; } IPv4InterfaceProperties p = ipprops.GetIPv4Properties(); if (null == p) { continue; // IPv4 is not configured on this adapter } int index = IPAddress.HostToNetworkOrder(p.Index); IPAddress addr = adapter.GetIPProperties().UnicastAddresses.Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork).Single().Address; UdpClient _udpClient = new UdpClient(new IPEndPoint(addr, GetFreePort())); _udpClient.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, index); _udpList.Add(_udpClient); Debug.WriteLine("Binded to " + adapter.Name); } } else { UdpClient _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, Port)); _udpList.Add(_udpClient); Debug.WriteLine("Binded to default"); } ProcessSendMessages(); foreach (UdpClient client in _udpList) { ProcessReceivingMessages(client); } }
/// <summary> /// Gets the available interfaces that are enabled for DHCP. /// </summary> /// <remarks> /// The operational status of the interface is not assessed. /// </remarks> /// <returns></returns> public static IEnumerable <NetworkInterface> GetDhcpInterfaces() { foreach (var nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.NetworkInterfaceType != NetworkInterfaceType.Ethernet || !nic.Supports(NetworkInterfaceComponent.IPv4)) { continue; } IPv4InterfaceProperties v4props = nic.GetIPProperties()?.GetIPv4Properties(); if (v4props == null || !v4props.IsDhcpEnabled) { continue; } yield return(nic); } }
internal static int GetInterfaceIndex(NetworkInterface nic, string networkAdapterName, bool throwOnError = true) { DeployerTrace.WriteInfo("Calling GetIPProperties() for network adapter {0}", networkAdapterName); IPInterfaceProperties ipProperties = nic.GetIPProperties(); if (ipProperties == null) { var message = string.Format( CultureInfo.CurrentUICulture, StringResources.Warning_FabricDeployer_DockerDnsSetup_GetIPPropertiesError, networkAdapterName); DeployerTrace.WriteWarning(message); if (throwOnError) { throw new InvalidOperationException(message); } return(-1); } DeployerTrace.WriteInfo("Calling GetIPv4Properties() for network adapter {0}", networkAdapterName); IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); if (ipv4Properties == null) { var message = string.Format( CultureInfo.CurrentUICulture, StringResources.Warning_FabricDeployer_DockerDnsSetup_GetIPv4PropertiesError, networkAdapterName); DeployerTrace.WriteWarning(message); if (throwOnError) { throw new InvalidOperationException(message); } return(-1); } DeployerTrace.WriteInfo("Returning InterfaceIndex: {0} for network adapter {1}", ipv4Properties.Index, networkAdapterName); return(ipv4Properties.Index); }
public WatchController(MainWindow window) { udpClient_ = new UdpClient(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.Name == "wlan0") { IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties(); foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { this.LocalIP = ip.Address.ToString(); Console.WriteLine(ip.Address.ToString()); break; } } //Console.WriteLine (adapter.GetIPProperties().); udpClient_.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, (int)IPAddress.HostToNetworkOrder(p.Index)); Console.WriteLine("assigned " + adapter.Name + " as multicast address : " + (int)IPAddress.HostToNetworkOrder(p.Index)); } } IPEndPoint localEp; localEp = new IPEndPoint(IPAddress.Any, PORT_NUMBER); udpClient_.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient_.ExclusiveAddressUse = false; udpClient_.Client.Bind(localEp); IPAddress multicastaddress = IPAddress.Parse(MULTICAST_IP); udpClient_.JoinMulticastGroup(multicastaddress); watches_ = new List <WatchModel>(); watchModel_ = new WatchModel(LocalIP, new Position(32, 32), 1); watches_.Add(watchModel_); }
private static int GetIndex(NetworkInterface ni) { IPInterfaceProperties ipprops = ni.GetIPProperties(); IPv4InterfaceProperties ipv4props = GetIPv4Properties(ipprops); if (ipv4props != null) { return(ipv4props.Index); } else if (Java_java_net_InetAddressImplFactory.isIPv6Supported()) { IPv6InterfaceProperties ipv6props = GetIPv6Properties(ipprops); if (ipv6props != null) { return(ipv6props.Index); } } return(-1); }
public static NetworkInterface[] GetUsableNics() { List <NetworkInterface> ret = new List <NetworkInterface>(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { switch (adapter.NetworkInterfaceType) { case NetworkInterfaceType.Ethernet: case NetworkInterfaceType.Ethernet3Megabit: case NetworkInterfaceType.FastEthernetFx: case NetworkInterfaceType.FastEthernetT: case NetworkInterfaceType.GigabitEthernet: case NetworkInterfaceType.Wireless80211: break; default: continue; } IPInterfaceProperties ip_properties = adapter.GetIPProperties(); if (!adapter.GetIPProperties().MulticastAddresses.Any()) { continue; // most of VPN adapters will be skipped } if (!adapter.SupportsMulticast) { continue; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != adapter.OperationalStatus) { continue; // this adapter is off or not connected } IPv4InterfaceProperties p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) { continue; // IPv4 is not configured on this adapter } ret.Add(adapter); } return(ret.ToArray()); }