如何在Win 10 UWP项目中找到本地IP地址

时间:2015-11-18 01:48:06

标签: c# ip uwp

我目前正在尝试将管理控制台应用程序移植到Win 10 UWP应用程序。我在使用以下控制台代码中的System.Net.Dns时遇到问题。

如何获取设备IP

以下是我尝试移植的控制台应用程序代码。

public static string GetIP4Address()
{
    string IP4Address = String.Empty;
    foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (IPA.AddressFamily == AddressFamily.InterNetwork)
        {
            IP4Address = IPA.ToString();
            break;
        }
    }
    return IP4Address;
}

3 个答案:

答案 0 :(得分:13)

使用它来获取UWP应用程序中的主机IP地址,我已经测试过了:

    foreach (HostName localHostName in NetworkInformation.GetHostNames())
    {
        if (localHostName.IPInformation != null)
        {
            if (localHostName.Type == HostNameType.Ipv4)
            {
                textblock.Text = localHostName.ToString();
                break;
            }
        }
    }

请参阅API文档here

答案 1 :(得分:11)

您可以尝试这样:

private string GetLocalIp()
{
    var icp = NetworkInformation.GetInternetConnectionProfile();

    if (icp?.NetworkAdapter == null) return null;
    var hostname =
        NetworkInformation.GetHostNames()
            .SingleOrDefault(
                hn =>
                    hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
                    == icp.NetworkAdapter.NetworkAdapterId);

    // the ip address
    return hostname?.CanonicalName;
}

上面的答案也是正确的

答案 2 :(得分:4)

基于@John Zhang的回答,但修复了不抛出多个匹配的LINQ错误并返回Ipv4地址:

   public static string GetLocalIp(HostNameType hostNameType = HostNameType.Ipv4)
    {
        var icp = NetworkInformation.GetInternetConnectionProfile();

        if (icp?.NetworkAdapter == null) return null;
        var hostname =
            NetworkInformation.GetHostNames()
                .FirstOrDefault(
                    hn =>
                        hn.Type == hostNameType &&
                        hn.IPInformation?.NetworkAdapter != null && 
                        hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId);

        // the ip address
        return hostname?.CanonicalName;
    }

显然你可以传递HostNameType.Ipv6而不是Ipv4,这是默认(隐式)参数值来获取Ipv6地址