[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); } }
void FindNetworkInterfaces() { var nics = NetworkInterface.GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == OperationalStatus.Up) .Where(nic => nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(nic => nic.SupportsMulticast) .Where(nic => !knownNics.Any(k => k.Id == nic.Id)) .ToArray(); foreach (var nic in nics) { lock (socketLock) { if (socket == null) { return; } IPInterfaceProperties properties = nic.GetIPProperties(); if (ip6) { var interfaceIndex = properties.GetIPv6Properties().Index; var mopt = new IPv6MulticastOption(MulticastAddressIp6, interfaceIndex); socket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mopt); maxPacketSize = Math.Min(maxPacketSize, properties.GetIPv6Properties().Mtu - packetOverhead); } else { var interfaceIndex = properties.GetIPv4Properties().Index; var mopt = new MulticastOption(MulticastAddressIp4, interfaceIndex); socket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mopt); maxPacketSize = Math.Min(maxPacketSize, properties.GetIPv4Properties().Mtu - packetOverhead); } knownNics.Add(nic); } } // Tell others. if (nics.Length > 0) { lock (socketLock) { if (socket == null) { return; } NetworkInterfaceDiscovered?.Invoke(this, new NetworkInterfaceEventArgs { NetworkInterfaces = nics }); } } }
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); }
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); }
static public List <IPInterfaceProperties> GetAllAddresses(AddressFamily addressFamily) { if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6) { throw new InvalidOperationException("AddressFamily either IPv4 or IPv6"); } List <IPInterfaceProperties> result = new List <IPInterfaceProperties>(); NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface netInterface in ifs) { IPInterfaceProperties ipProps = netInterface.GetIPProperties(); // if (netInterface.GetIPProperties().MulticastAddresses.Count == 0) // continue; // most of VPN adapters will be skipped if (!netInterface.SupportsMulticast) { continue; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != netInterface.OperationalStatus) { continue; // this adapter is off or not connected } if ((addressFamily == AddressFamily.InterNetwork && ipProps.GetIPv4Properties() == null) || (addressFamily == AddressFamily.InterNetworkV6 && ipProps.GetIPv6Properties() == null)) { continue; // IPv4 is not configured on this adapter } result.Add(ipProps); } return(result); }
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 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)); }
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); }
/// <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"); }
bool getGateWay() { gateway = null; NetworkInterface gatewayData = GetDefaultGateway(); if (gatewayData != null) { IPInterfaceProperties gateProps = gatewayData.GetIPProperties(); foreach (var gateAd in gateProps.GatewayAddresses) { if (!gateAd.Address.IsIPv6LinkLocal) { gateway = gateAd.Address; break; } } gatewayIndex = gateProps.GetIPv4Properties().Index; return(true); } else { return(false); } }
public static bool IS_DHCP()//是否开启DHCP { NetworkInterface[] adapter = NetworkInterface.GetAllNetworkInterfaces(); IPInterfaceProperties ipp = adapter[0].GetIPProperties(); IPv4InterfaceProperties ip4ip = ipp.GetIPv4Properties(); return(ip4ip.IsDhcpEnabled); }
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 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 }); } } } }
private static IPv4InterfaceProperties GetIPv4Properties(IPInterfaceProperties props) { try { return(props.GetIPv4Properties()); } catch (NetworkInformationException) { return(null); } }
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); }
private void DefaultNetworkDnsMenuItem_Click(object sender, EventArgs e) { if (!Program.IsAdmin) { Program.RunAsAdmin("--network-dns-default"); return; } try { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } SetNameServerIPv6(nic, Array.Empty <IPAddress>()); try { IPInterfaceProperties properties = nic.GetIPProperties(); if (properties.GetIPv4Properties().IsDhcpEnabled) { SetNameServerIPv4(nic, Array.Empty <IPAddress>()); } else if (properties.GatewayAddresses.Count > 0) { SetNameServerIPv4(nic, new IPAddress[] { properties.GatewayAddresses[0].Address }); } else { SetNameServerIPv4(nic, Array.Empty <IPAddress>()); } } catch (NetworkInformationException) { } } MessageBox.Show("The network DNS servers were set to default successfully.", "Default DNS Set - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("Error occured while setting default network DNS servers. " + ex.Message, "Error - " + Resources.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void AddStatisticAddressesInformation(ListView lst, WlanClient.WlanInterface wlanIface) { ListViewGroup group = new ListViewGroup("Addresses"); lst.Groups.Add(group); List <ListViewItem> items = new List <ListViewItem>(); IPInterfaceProperties interfaceProperties = wlanIface.NetworkInterface.GetIPProperties(); for (int i = 0; i < interfaceProperties.UnicastAddresses.Count; i++) { items.Add( Utils.MakeKeyValueItem($"Addresses #{i}", $"{interfaceProperties.UnicastAddresses[i].Address.ToString()}", group) ); } for (int i = 0; i < interfaceProperties.GatewayAddresses.Count; i++) { items.Add( Utils.MakeKeyValueItem($"GatewayAddresses #{i}", $"{interfaceProperties.GatewayAddresses[i].Address.ToString()}", group) ); } if (interfaceProperties.GetIPv4Properties().IsDhcpEnabled) { for (int i = 0; i < interfaceProperties.DhcpServerAddresses.Count; i++) { items.Add( Utils.MakeKeyValueItem($"DhcpServerAddress #{i}", $"{interfaceProperties.DhcpServerAddresses[i].ToString()}", group) ); } } for (int i = 0; i < interfaceProperties.DnsAddresses.Count; i++) { items.Add( Utils.MakeKeyValueItem($"DnsAddress #{i}", $"{interfaceProperties.DnsAddresses[i].ToString()}", group) ); } lst.Items.AddRange(items.ToArray()); }
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); } } }
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); } }
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(); } }
/// <summary> /// Returns an appropriate NetworkInterface object for the specified interface index. /// </summary> /// <param name="interfaceIndex">The index of the interface for which to retrieve a NetworkInterface object.</param> public static NetworkInterface GetNetworkInterface(uint interfaceIndex) { foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = item.GetIPProperties(); if (item.Supports(NetworkInterfaceComponent.IPv4) && properties.GetIPv4Properties().Index == interfaceIndex) { return(item); } if (item.Supports(NetworkInterfaceComponent.IPv6) && properties.GetIPv6Properties().Index == interfaceIndex) { return(item); } } throw new ArgumentOutOfRangeException(nameof(interfaceIndex)); }
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); }
private IList <IPAddress> GetLocalEndpoints() { //var interfaces = new Dictionary<int, IPInterfaceProperties>(); var addresses = new List <IPAddress>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } if (nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } IPInterfaceProperties ipProps = nic.GetIPProperties(); try { var ipv4Props = ipProps.GetIPv4Properties(); if (ipv4Props == null) { continue; } //interfaces.Add(ipv4Props.Index, ipProps); addresses.AddRange( ipProps.UnicastAddresses.Where(u => u.Address.AddressFamily.Equals(AddressFamily.InterNetwork)) .Select(x => x.Address)); } catch (NetworkInformationException ex) { Console.WriteLine("Interface doesn't have any IPv4 properties {0}", nic.Name); } } return(addresses); //var firstInterface = interfaces.OrderBy(i => i.Key).FirstOrDefault(); //var ipAddress = firstInterface.Value.UnicastAddresses.First(ip => !ip.Address.IsIPv6LinkLocal); //return ipAddress.Address; }
public static void ShowNetworkInfo() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); Console.WriteLine(adapter.Name); Console.WriteLine(adapter.Description); Console.WriteLine(adapter.GetPhysicalAddress().ToString()); Console.WriteLine(properties.GetIPv4Properties().Index.ToString()); Console.WriteLine(properties.UnicastAddresses.Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork).ToList().Select(i => i.Address.ToString()).Aggregate((i, j) => i + "," + j)); if (properties.GatewayAddresses.Count > 0) { Console.WriteLine(properties.GatewayAddresses.Where(i => i != null && i.Address != null).ToList().Select(i => i.Address.ToString()).Aggregate((i, j) => i + "," + j)); } Console.WriteLine("======================================================================="); } }
public static string getLocalIPv4Address() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 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(); Console.WriteLine(); } return(""); }
private static IPv4InterfaceProperties GetIPv4Properties(IPInterfaceProperties props) { try { return props.GetIPv4Properties(); } catch (NetworkInformationException) { return null; } }