private static IEnumerable <NetworkInterface> GetInternetNetworkInterfaces() { var networkInterfaces = new List <NetworkInterface>(); foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = networkInterface.GetIPProperties(); bool isInternet = networkInterface.OperationalStatus == OperationalStatus.Up && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ppp && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback && (properties.IsDnsEnabled || properties.IsDynamicDnsEnabled); if (!isInternet) { continue; } networkInterfaces.Add(networkInterface); } return(networkInterfaces); }
// </snippet3> // <snippet4> public static PhysicalAddress[] StoreNetworkInterfaceAddresses() { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); if (nics == null || nics.Length < 1) { Console.WriteLine(" No network interfaces found."); return(null); } PhysicalAddress[] addresses = new PhysicalAddress[nics.Length]; int i = 0; foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); PhysicalAddress address = adapter.GetPhysicalAddress(); byte[] bytes = address.GetAddressBytes(); PhysicalAddress newAddress = new PhysicalAddress(bytes); addresses[i++] = newAddress; } return(addresses); }
/// <summary> /// Gets my local IPv4 address (not necessarily external) and subnet mask /// </summary> public static IPAddress GetMyAddress(out IPAddress mask) { var ni = GetNetworkInterface(); if (ni == null) { mask = null; return(null); } IPInterfaceProperties properties = ni.GetIPProperties(); foreach (UnicastIPAddressInformation unicastAddress in properties.UnicastAddresses) { if (unicastAddress != null && unicastAddress.Address != null && unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork) { mask = unicastAddress.IPv4Mask; return(unicastAddress.Address); } } mask = null; return(null); }
private static bool HasPublicIPAddress() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties properties = adapter.GetIPProperties(); foreach (IPAddressInformation unicast in properties.UnicastAddresses) { IPAddress ip = unicast.Address; if (!IPAddress.IsLoopback(ip) && ip.AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork(ip)) { return(true); } } } return(false); /* * IPHostEntry iphe = Dns.GetHostEntry( Dns.GetHostName() ); * * IPAddress[] ips = iphe.AddressList; * * for ( int i = 0; i < ips.Length; ++i ) * { * if ( ips[i].AddressFamily != AddressFamily.InterNetworkV6 && !IsPrivateNetwork( ips[i] ) ) * return true; * } * * return false; */ }
public static List <IPAndMask> GetAllLocalIPAddressesAndMasks() { List <IPAndMask> ips = new List <IPAndMask>(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.OperationalStatus == OperationalStatus.Up && nic.Supports(NetworkInterfaceComponent.IPv4)) { IPInterfaceProperties properties = nic.GetIPProperties(); UnicastIPAddressInformationCollection unicast = properties.UnicastAddresses; foreach (UnicastIPAddressInformation unicastIP in unicast) { if (unicastIP.Address.AddressFamily == AddressFamily.InterNetwork) { ips.Add(new IPAndMask { Address = unicastIP.Address, SubnetMask = unicastIP.IPv4Mask }); } } } } return(ips); }
public void IPv6ScopeId_AccessAllValues_Success() { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPInterfaceProperties ipProperties = nic.GetIPProperties(); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); Array values = Enum.GetValues(typeof(ScopeLevel)); foreach (ScopeLevel level in values) { Assert.Throws <PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(level)); } } }
void SearchDevice_Execute(object parameters) { foreach (NetworkInterface Interface in NetworkInterface.GetAllNetworkInterfaces()) { if (Interface.SupportsMulticast) { IPInterfaceProperties IPProperties = Interface.GetIPProperties(); foreach (IPAddressInformation address in IPProperties.UnicastAddresses) { // The following information is not useful for loopback adapters. if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } Console.WriteLine(Interface.Name); if (address.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { this.DiscoverDevices(address); } } } } }
public async Task IPInfoTest_AccessAllIPv4Properties_NoErrors() { await Task.Run(() => { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv4 Properties:"); IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); _log.WriteLine("Index: " + ipv4Properties.Index); Assert.Throws <PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingActive); Assert.Throws <PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingEnabled); Assert.Throws <PlatformNotSupportedException>(() => ipv4Properties.IsDhcpEnabled); Assert.Throws <PlatformNotSupportedException>(() => ipv4Properties.IsForwardingEnabled); _log.WriteLine("Mtu: " + ipv4Properties.Mtu); Assert.Throws <PlatformNotSupportedException>(() => ipv4Properties.UsesWins); } }).WaitAsync(TestHelper.PassingTestTimeout); }
/// <summary> /// hàm thực hiện việc lấy thông tin của địa chỉ mac cho máy tính /// </summary> /// <returns></returns> public static string GetMACAddress() { try { if (string.IsNullOrEmpty(globalVariables.IpMacAddress)) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (NetworkInterface adapter in nics) { if (sMacAddress == String.Empty)// only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIPProperties(); sMacAddress = adapter.GetPhysicalAddress().ToString(); globalVariables.IpMacAddress = sMacAddress; } } } // Utility.sDbnull() return(globalVariables.IpMacAddress); } catch { return("NO-ADDRESS"); } }
private static string FormatIPInterfaceProperties(IPInterfaceProperties adapterProperties) { string result = string.Empty; try { result += FormatIPAddressInformationCollection(adapterProperties.AnycastAddresses, " Anycast address: {0} (Transient: {1}; DNS eligible: {2})\n"); } catch (PlatformNotSupportedException) { } result += FormatIPAddressCollection(adapterProperties.DhcpServerAddresses, " DHCP server: {0}\n"); result += FormatIPAddressCollection(adapterProperties.DnsAddresses, " DNS server: {0}\n"); result += $" DNS suffix: {adapterProperties.DnsSuffix}\n"; result += FormatGatewayIPAddressInformationCollection(adapterProperties.GatewayAddresses); result += $" DNS enabled: {adapterProperties.IsDnsEnabled}\n"; result += $" Dynamic DNS enabled: {adapterProperties.IsDnsEnabled}\n"; result += FormatMulticastIPAddressInformationCollection(adapterProperties.MulticastAddresses); result += FormatUnicastIPAddressInformationCollection(adapterProperties.UnicastAddresses); result += FormatIPAddressCollection(adapterProperties.WinsServersAddresses, " WINS server: {0}\n"); return(result); }
private void refreshNICList(Boolean showHidden) { this.ipv6Radio.Enabled = false; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); NetworkListItem item = new NetworkListItem(adapter.Name, adapter.Description, adapter.Id, adapter.Supports(NetworkInterfaceComponent.IPv4), adapter.Supports(NetworkInterfaceComponent.IPv6)); if (!item.getHidden() || showHidden) { List <string> dnsList = new List <string>(); object dnsResult = Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" + item.getID(), "NameServer", ""); if (dnsResult != null && dnsResult.ToString().Length > 0) { dnsList = new List <string>(((string)dnsResult).Split(new string[] { "," }, System.StringSplitOptions.None)); } if (dnsList.Count != 0 && dnsList[0] == "127.0.0.1") { DNSlistbox.Items.Add(item, true); } else { DNSlistbox.Items.Add(item); } if (item.getIpv6()) { this.ipv6Radio.Enabled = true; } } } }
public void ListIpAddresses() { foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()) { Console.WriteLine("Network Interface: {0}", netif.Name); IPInterfaceProperties properties = netif.GetIPProperties(); foreach (IPAddress dns in properties.DnsAddresses) { Console.WriteLine("\tDNS: {0}", dns); } foreach (IPAddressInformation anycast in properties.AnycastAddresses) { Console.WriteLine("\tAnyCast: {0}", anycast.Address); } foreach (IPAddressInformation multicast in properties.MulticastAddresses) { Console.WriteLine("\tMultiCast: {0}", multicast.Address); } foreach (IPAddressInformation unicast in properties.UnicastAddresses) { Console.WriteLine("\tUniCast: {0}", unicast.Address); } } }
private static string GetAnyHostAddress() { string result = ""; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { IPInterfaceProperties pix = adapter.GetIPProperties(); UnicastIPAddressInformationCollection ipCollection = pix.UnicastAddresses; foreach (UnicastIPAddressInformation ipaddr in ipCollection) { if (ipaddr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { result = ipaddr.Address.ToString(); break; } } } } return(result); }
internal static IPAddress[] GetLocalAddresses(int ipVersion, bool includeLoopback, bool singleAddressPerInterface) { List <IPAddress> addresses = new List <IPAddress>(); try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in nics) { IPInterfaceProperties ipProps = ni.GetIPProperties(); UnicastIPAddressInformationCollection uniColl = ipProps.UnicastAddresses; foreach (UnicastIPAddressInformation uni in uniColl) { if ((uni.Address.AddressFamily == AddressFamily.InterNetwork && ipVersion != EnableIPv6) || (uni.Address.AddressFamily == AddressFamily.InterNetworkV6 && ipVersion != EnableIPv4)) { if (!addresses.Contains(uni.Address) && (includeLoopback || !IPAddress.IsLoopback(uni.Address))) { addresses.Add(uni.Address); if (singleAddressPerInterface) { break; } } } } } } catch (Exception ex) { throw new TransportException("error retrieving local network interface IP addresses", ex); } return(addresses.ToArray()); }
private static string[] GetAdapterIpAdresses(NetworkInterface adapter) { if (adapter == null) { throw new Exception("No network interfaces found"); } IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); string[] s = null; IPAddressCollection dnsServers = adapterProperties.DnsAddresses; if (dnsServers != null) { s = new string[dnsServers.Count]; int i = 0; foreach (IPAddress dns in dnsServers) { s[i] = dns.ToString(); i++; } } return(s); }
static public string LeerMacAddress() { NetworkInterface[] nets = NetworkInterface.GetAllNetworkInterfaces(); string mac = ""; foreach (NetworkInterface adapter in nets) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { IPInterfaceProperties properties = adapter.GetIPProperties(); PhysicalAddress address = adapter.GetPhysicalAddress(); byte[] bytes = address.GetAddressBytes(); for (int i = 0; i < bytes.Length; i++) { mac += bytes[i].ToString("X2"); if (i != bytes.Length - 1) { mac += "-"; } } } } return(mac); }
private void aboutDHCP_Click(object sender, EventArgs e) { resultInfo.Clear(); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPAddressCollection addresses = adapterProperties.DhcpServerAddresses; if (addresses.Count > 0) { resultInfo.Text += adapter.Description + '\n'; foreach (IPAddress address in addresses) { resultInfo.Text += "Адрес: " + address.ToString() + '\n'; } resultInfo.Text += '\n'; } } }
private string getMachineIp() { if (NetworkInterface.GetIsNetworkAvailable()) { foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { if (networkInterface.OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties ipproperties = networkInterface.GetIPProperties(); if (ipproperties.GatewayAddresses.FirstOrDefault <GatewayIPAddressInformation>() != null) { foreach (UnicastIPAddressInformation unicastIPAddressInformation in ipproperties.UnicastAddresses) { if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { return(unicastIPAddressInformation.Address.ToString()); } } } } } } return(string.Empty); }
void SslPopulateIPs() { this.sslAddress.Items.Clear(); this.sslAddress.Items.Add(IPAddress.Any); this.sslAddress.SelectedIndex = 0; this.sslAddress.Items.Add(IPAddress.IPv6Any); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { if (adapter.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); foreach (IPAddressInformation address in adapterProperties.AnycastAddresses) { this.sslAddress.Items.Add(address.Address); } foreach (IPAddressInformation address in adapterProperties.UnicastAddresses) { this.sslAddress.Items.Add(address.Address); } } }
/// <summary> /// Creates and returns a fully configured <see cref="ILogProvider"/> instance. /// </summary> /// <returns>A fully configured <see cref="ILogProvider"/> instance.</returns> public ILogProvider GetConfiguredInstance() { NetworkInterfaceWrapper adapter = cmbNetworkInterface.SelectedItem as NetworkInterfaceWrapper; if (adapter != null) { IPInterfaceProperties ipInfo = adapter.Adapter.GetIPProperties(); if (ipInfo != null) { foreach (UnicastIPAddressInformation ipAddress in ipInfo.UnicastAddresses) { if (ipAddress.Address != null && ipAddress.Address.AddressFamily == AddressFamily.InterNetwork) { if (ModifierKeys != Keys.Shift) { // Save the current settings as new default values. Settings.Default.PnlCustomTcpSettingsInterface = cmbNetworkInterface.SelectedItem.ToString(); Settings.Default.PnlCustomTcpSettingsPort = (int)nudPort.Value; Settings.Default.PnlCustomTcpSettingsEncoding = ((EncodingWrapper)cmbEncoding.SelectedItem).Codepage; Settings.Default.SaveSettings(); } return(new CustomTcpReceiver( (int)nudPort.Value , new IPEndPoint(ipAddress.Address, (int)nudPort.Value) , cmbColumnizer.SelectedItem as Columnizer , Settings.Default.PnlCustomTcpSettingsEncoding)); } } } } return(null); }
private List <String> GetIpListOfTheNetInterface() { List <String> ipList = new List <string>(); NetworkInterface[] NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface NetworkIntf in NetworkInterfaces) { IPInterfaceProperties IPInterfaceProperties = NetworkIntf.GetIPProperties(); UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = IPInterfaceProperties.UnicastAddresses; foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection) { if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { String ip = UnicastIPAddressInformation.Address.ToString(); if (!ip.Equals("127.0.0.1")) { ipList.Add(ip); } } } } return(ipList); }
public static List <IPAddress> GetMachineDnsServers() { List <IPAddress> dnsServers = new List <IPAddress>(); //IPAddressCollection dnsServers = null; IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties properties = adapter.GetIPProperties(); foreach (IPAddress ipAddress in properties.DnsAddresses) { dnsServers.Add(ipAddress); } } } return(dnsServers); }
//Метод получения МАС и дописывание его последней строкой в файл public string GetMACAddress() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); String sMacAddress = string.Empty; foreach (NetworkInterface adapter in nics) { if (sMacAddress == String.Empty)// only return MAC Address from first card { IPInterfaceProperties properties = adapter.GetIPProperties(); sMacAddress = adapter.GetPhysicalAddress().ToString(); //отправляем мас в лейбл label5.Text = sMacAddress; try { System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\Processes.txt", true); writer.WriteLine("МАС of user: " + sMacAddress); writer.Close(); } catch (System.IO.IOException) { } } } return(sMacAddress); }
public void AtLeastOneGatewayAddress() { int numGatewayAddresses = 0; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); // On Android (possibly on other systems too) it is possible that no gateway address is available and its lack is NOT an error // Here is a sample of /proc/net/route from Nexus 9 running Android 5.1.1 (IPInterfaceProperties parses that file on Linux) // // Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT // wlan0 0001A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 // // Gateway is set to any address and it is explicitly ignored by the route information parser // // For comparison, here's route contents from an Android 4.4.4 device: // // Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT // wlan0 00000000 0101A8C0 0003 0 0 0 00000000 0 0 0 // wlan0 00000000 0101A8C0 0003 0 0 203 00000000 0 0 0 // wlan0 0001A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 // wlan0 0001A8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 // wlan0 0001A8C0 00000000 0001 0 0 203 00FFFFFF 0 0 0 // wlan0 0101A8C0 00000000 0005 0 0 0 FFFFFFFF 0 0 0 // // Obviously, this test fails on the first device and succeeds on the second. For this reason the test is modified to succeed // in case of devices like the first one since it's not a real failure but a shortcoming of the .NET API // foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); GatewayIPAddressInformationCollection gatewayAddresses = adapterProperties.GatewayAddresses; numGatewayAddresses += HasOnlyDefaultGateway(adapter.Name) ? 1 : gatewayAddresses.Count; } Assert.IsTrue(numGatewayAddresses > 0); }
public static async Task WakeOnLan(string macAddress) { Console.WriteLine("已经向" + macAddress + "发送唤醒包"); byte[] magicPacket = BuildMagicPacket(macAddress); foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces().Where((n) => n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.OperationalStatus == OperationalStatus.Up)) { IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties(); foreach (MulticastIPAddressInformation multicastIPAddressInformation in iPInterfaceProperties.MulticastAddresses) { IPAddress multicastIpAddress = multicastIPAddressInformation.Address; if (multicastIpAddress.ToString().StartsWith("ff02::1%", StringComparison.OrdinalIgnoreCase)) // Ipv6: All hosts on LAN (with zone index) { UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetworkV6 && !u.Address.IsIPv6LinkLocal).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); break; } } else if (multicastIpAddress.ToString().Equals("224.0.0.1")) // Ipv4: All hosts on LAN { UnicastIPAddressInformation unicastIPAddressInformation = iPInterfaceProperties.UnicastAddresses.Where((u) => u.Address.AddressFamily == AddressFamily.InterNetwork && !iPInterfaceProperties.GetIPv4Properties().IsAutomaticPrivateAddressingActive).FirstOrDefault(); if (unicastIPAddressInformation != null) { await SendWakeOnLan(unicastIPAddressInformation.Address, multicastIpAddress, magicPacket); break; } } } } }
Boolean GetMAC(string dbMAC, bool t) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); PhysicalAddress address = adapter.GetPhysicalAddress(); EducationDataContext loMacContext = new EducationDataContext(); if (adapter.OperationalStatus.ToString() == "Up" && t == true && (adapter.NetworkInterfaceType.ToString() == "Ethernet" || adapter.Name == "Wi-Fi")) { loMacContext.InsertMACAddress(address.ToString(), Session["UserID"]); Session["MAC"] = address.ToString(); return(false); } if (adapter.OperationalStatus.ToString() == "Up" && dbMAC != null && (adapter.NetworkInterfaceType.ToString() == "Ethernet" || adapter.Name == "Wi-Fi")) { if (dbMAC == address.ToString()) { return(true); } } } return(false); }
public static NetworkInfo GetDefaultIPv6NetworkInfo() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties ipInterface = nic.GetIPProperties(); foreach (GatewayIPAddressInformation gateway in ipInterface.GatewayAddresses) { if (gateway.Address.AddressFamily == AddressFamily.InterNetworkV6) { IPAddress ipv6 = null; foreach (UnicastIPAddressInformation ip in ipInterface.UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6) { if (IsPublicIPv6(ip.Address)) { if (ip.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred) { if (ip.SuffixOrigin == SuffixOrigin.Random) { return(new NetworkInfo(nic, ip.Address)); } ipv6 = ip.Address; } } } } if (ipv6 != null) { return(new NetworkInfo(nic, ipv6)); } break; } } } foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties ipInterface = nic.GetIPProperties(); IPAddress ipv6 = null; foreach (UnicastIPAddressInformation ip in ipInterface.UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6) { if (IsPublicIPv6(ip.Address)) { if (ip.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred) { if (ip.SuffixOrigin == SuffixOrigin.Random) { return(new NetworkInfo(nic, ip.Address)); } ipv6 = ip.Address; } } } } if (ipv6 != null) { return(new NetworkInfo(nic, ipv6)); } } return(null); }
public static NetworkInfo GetNetworkInfo(IPAddress destinationIP) { if (destinationIP.IsIPv4MappedToIPv6) { destinationIP = destinationIP.MapToIPv4(); } byte[] destination = destinationIP.GetAddressBytes(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties ipInterface = nic.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipInterface.UnicastAddresses) { if (ip.Address.AddressFamily == destinationIP.AddressFamily) { switch (destinationIP.AddressFamily) { case AddressFamily.InterNetwork: #region ipv4 { byte[] addr = ip.Address.GetAddressBytes(); byte[] mask; try { mask = ip.IPv4Mask.GetAddressBytes(); } catch (NotImplementedException) { //method not implemented in mono framework for Linux if (addr[0] == 10) { mask = new byte[] { 255, 0, 0, 0 }; } else if ((addr[0] == 192) && (addr[1] == 168)) { mask = new byte[] { 255, 255, 255, 0 }; } else if ((addr[0] == 169) && (addr[1] == 254)) { mask = new byte[] { 255, 255, 0, 0 }; } else if ((addr[0] == 172) && (addr[1] > 15) && (addr[1] < 32)) { mask = new byte[] { 255, 240, 0, 0 }; } else { mask = new byte[] { 255, 255, 255, 0 }; } } catch { continue; } bool isInSameNetwork = true; for (int i = 0; i < 4; i++) { if ((addr[i] & mask[i]) != (destination[i] & mask[i])) { isInSameNetwork = false; break; } } if (isInSameNetwork) { return(new NetworkInfo(nic, ip.Address, new IPAddress(mask))); } } #endregion break; case AddressFamily.InterNetworkV6: #region ipv6 { if (destinationIP.ScopeId > 0) { if (destinationIP.ScopeId == ip.Address.ScopeId) { return(new NetworkInfo(nic, ip.Address)); } } else { byte[] addr = ip.Address.GetAddressBytes(); bool isInSameNetwork = true; for (int i = 0; i < 8; i++) { if (addr[i] != destination[i]) { isInSameNetwork = false; break; } } if (isInSameNetwork) { return(new NetworkInfo(nic, ip.Address)); } } } #endregion break; } } } } if (destinationIP.AddressFamily == AddressFamily.InterNetworkV6) { return(GetDefaultIPv6NetworkInfo()); } else { return(GetDefaultIPv4NetworkInfo()); } }
public static NetworkInfo GetDefaultIPv4NetworkInfo() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus != OperationalStatus.Up) { continue; } IPInterfaceProperties ipInterface = nic.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipInterface.UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { byte[] addr = ip.Address.GetAddressBytes(); byte[] mask; try { mask = ip.IPv4Mask.GetAddressBytes(); } catch (NotImplementedException) { //method not implemented in mono framework for Linux if (addr[0] == 10) { mask = new byte[] { 255, 0, 0, 0 }; } else if ((addr[0] == 192) && (addr[1] == 168)) { mask = new byte[] { 255, 255, 255, 0 }; } else if ((addr[0] == 169) && (addr[1] == 254)) { mask = new byte[] { 255, 255, 0, 0 }; } else if ((addr[0] == 172) && (addr[1] > 15) && (addr[1] < 32)) { mask = new byte[] { 255, 240, 0, 0 }; } else { mask = new byte[] { 255, 255, 255, 0 }; } } catch { continue; } foreach (GatewayIPAddressInformation gateway in ipInterface.GatewayAddresses) { if (gateway.Address.AddressFamily == AddressFamily.InterNetwork) { byte[] gatewayAddr = gateway.Address.GetAddressBytes(); bool isDefaultRoute = true; bool isInSameNetwork = true; for (int i = 0; i < 4; i++) { if (gatewayAddr[i] != 0) { isDefaultRoute = false; break; } } if (isDefaultRoute) { return(new NetworkInfo(nic, ip.Address, new IPAddress(mask))); } for (int i = 0; i < 4; i++) { if ((addr[i] & mask[i]) != (gatewayAddr[i] & mask[i])) { isInSameNetwork = false; break; } } if (isInSameNetwork) { return(new NetworkInfo(nic, ip.Address, new IPAddress(mask))); } } } } } } return(null); }
/// <summary> /// 通过mac地址获取ip地址 /// </summary> /// <param name="mac"></param> /// <param name="getIPV6"></param> /// <returns></returns> public static IPInfo GetIpAddressByMacAddress(string mac, bool getIPV6 = false) { bool found = false; string tmpMac = mac.Replace("-", "").Replace(":", "").ToUpper().Trim(); IPInfo ipInfo = new IPInfo(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (found) { break; } if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet || adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { string macadd = adapter.GetPhysicalAddress().ToString(); if (macadd.ToUpper().Trim().Equals(tmpMac)) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { //判断是否为ipv4 ipInfo.IpV4 = ipadd.Address.ToString().Trim(); } if (getIPV6) { if (ipadd.Address.AddressFamily == AddressFamily.InterNetworkV6) { //判断是否为ipv6 ipInfo.IpV6 = ipadd.Address.ToString().Trim(); } } if (getIPV6) { if (!string.IsNullOrEmpty(ipInfo.IpV4) && !string.IsNullOrEmpty(ipInfo.IpV6)) { found = true; break; } } else { if (!string.IsNullOrEmpty(ipInfo.IpV4)) { found = true; break; } } } } } } if (found) { return(ipInfo); } return(null !); }
#pragma warning restore 618 #if !UNITY_WEBPLAYER static bool IsValidInterface(NetworkInterface nic, IPInterfaceProperties p) { foreach (var addr in p.GatewayAddresses) { byte[] bytes = addr.Address.GetAddressBytes(); if (bytes.Length == 4 && bytes[0] != 0 && bytes[1] != 0 && bytes[2] != 0 && bytes[3] != 0) { return true; } } return false; }
private static IPv6InterfaceProperties GetIPv6Properties(IPInterfaceProperties props) { try { return props.GetIPv6Properties(); } catch (NetworkInformationException) { return null; } }
public static void ShowIPAddresses(IPInterfaceProperties adapterProperties) { IPAddressCollection dnsServers = adapterProperties.DnsAddresses; if (dnsServers != null) { foreach (IPAddress dns in dnsServers) { Console.WriteLine(" DNS Servers ............................. : {0}", dns.ToString() ); } } IPAddressInformationCollection anyCast = adapterProperties.AnycastAddresses; if (anyCast != null) { foreach (IPAddressInformation any in anyCast) { Console.WriteLine(" Anycast Address .......................... : {0} {1} {2}", any.Address, any.IsTransient ? "Transient" : "", any.IsDnsEligible ? "DNS Eligible" : "" ); } Console.WriteLine(); } MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses; if (multiCast != null) { foreach (IPAddressInformation multi in multiCast) { Console.WriteLine(" Multicast Address ....................... : {0} {1} {2}", multi.Address, multi.IsTransient ? "Transient" : "", multi.IsDnsEligible ? "DNS Eligible" : "" ); } Console.WriteLine(); } UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast != null) { string lifeTimeFormat = "dddd, MMMM dd, yyyy hh:mm:ss tt"; foreach (UnicastIPAddressInformation uni in uniCast) { DateTime when; Console.WriteLine(" Unicast Address ......................... : {0}", uni.Address); Console.WriteLine(" Prefix Origin ........................ : {0}", uni.PrefixOrigin); Console.WriteLine(" Suffix Origin ........................ : {0}", uni.SuffixOrigin); Console.WriteLine(" Duplicate Address Detection .......... : {0}", uni.DuplicateAddressDetectionState); // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM // if en-us is the current culture. // Calculate the date and time at the end of the lifetimes. when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime); when = when.ToLocalTime(); Console.WriteLine(" Valid Life Time ...................... : {0}", when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture) ); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime); when = when.ToLocalTime(); Console.WriteLine(" Preferred life time .................. : {0}", when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture) ); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime); when = when.ToLocalTime(); Console.WriteLine(" DHCP Leased Life Time ................ : {0}", when.ToString(lifeTimeFormat,System.Globalization.CultureInfo.CurrentCulture) ); } Console.WriteLine(); } }