Windows phone8 获取本机 IP 地址

可以在 Bing 查找中输入: "my IP address",然后确认这样可以看到自己的 IP。

如果需要通过代码编程来获取本机 IP,可以使用以下代码:

注意:此段代码在 WP7.1 上无法编译通过,NetworkInformation 未定义。

public class GetHostIPAddress
    {
        public string GetIPAddress()
        {
            string strIPAddress = null;
            List<string> arrayIPAddress = new List<string>();
            // Windows.Networking.Connectivity.
            var hostNames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();
            foreach (var hn in hostNames)
            {
                if (hn.IPInformation != null)
                {
                    string ipAddress = hn.DisplayName;
                    arrayIPAddress.Add(ipAddress);
                }
            }
            if (arrayIPAddress.Count < 1)
            {
                return null;
            }
            if (arrayIPAddress.Count == 1)
            {
                strIPAddress = arrayIPAddress[0];
            }
            if (arrayIPAddress.Count > 1)
            {
                strIPAddress = arrayIPAddress[arrayIPAddress.Count - 1];
            }
            // System.Console.WriteLine();
            for (int i = 0; i < arrayIPAddress.Count;i++ )
            {
                System.Diagnostics.Debug.WriteLine("No.{0} host IP is: {1}",i + 1,arrayIPAddress[i]);
            }
            return strIPAddress;
        }
    }


调用示例:

{
      GetHostIPAddress hostIP = new GetHostIPAddress();
      hostIP.GetIPAddress();
}

运行输入如下所示:

No.1 host IP is: 169.254.135.85
No.2 host IP is: 169.254.162.98
No.3 host IP is: 192.168.0.101

 

你可能感兴趣的:(Windows phone8 获取本机 IP 地址)