如何在WP 8.1中获取设备IP

本文关键字:获取 IP WP | 更新日期: 2023-09-27 18:34:20

我只需要在本地网络中获取设备的当前IP。像...

var IP = IPInformation.GetIP();

对不起这个简单的问题...只是找不到东西。

如何在WP 8.1中获取设备IP

你需要

通过类(Windows.Networking.Connectivity.NetworkInformation)使用GetHostNames()方法NetworkInformation

您将检索包含所有 IP 地址的主机名对象集合(在DisplayName属性中)

List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
       {
         //IanaInterfaceType == 71 => Wifi
         //IanaInterfaceType == 6 => Ethernet (Emulator)
         if (hn.IPInformation != null && 
            (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71 
            || hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
               {
                  string ipAddress = hn.DisplayName;
                  ipAddresses.Add(ipAddress);
               }
        }

IPAddresses 方法获取选定的服务器 IP 地址信息。然后,它显示服务器支持的地址族类型及其标准和字节格式的 IP 地址。

 private static void IPAddresses(string server) 
    {
      try 
      {
        System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
        // Get server related information.
        IPHostEntry heserver = Dns.GetHostEntry(server);
        // Loop on the AddressList 
        foreach (IPAddress curAdd in heserver.AddressList) 
        {

          // Display the type of address family supported by the server. If the 
          // server is IPv6-enabled this value is: InternNetworkV6. If the server 
          // is also IPv4-enabled there will be an additional value of InterNetwork.
          Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());
          // Display the ScopeId property in case of IPV6 addresses. 
          if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
            Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());

          // Display the server IP address in the standard format. In  
          // IPv4 the format will be dotted-quad notation, in IPv6 it will be 
          // in in colon-hexadecimal notation.
          Console.WriteLine("Address: " + curAdd.ToString());
          // Display the server IP address in byte format.
          Console.Write("AddressBytes: ");

          Byte[] bytes = curAdd.GetAddressBytes();
          for (int i = 0; i < bytes.Length; i++) 
          {
            Console.Write(bytes[i]);
          }                          
          Console.WriteLine("'r'n");
        }
  }