查询本地IP地址(Query Local IP Address)

2019-06-24 00:22发布

我有必要从Windows 8的WinRT / Metro应用知道我的实际本地IP地址(即不是环回地址)。 有几个原因,我需要这个。 最简单的是,在应用程序的UI我想表现出像一些文字“您的局域网IP地址:IP从代码查询]”。

我们还使用地址一些额外的网络通讯科。 这些通讯科是完全有效的,因为这一切,如果我看在控制面板中的IP地址,然后硬编码到应用程序的工作原理。 在一个对话框,要求用户去看看地址,并手动输入它是我真的,​​真的希望避免的。

我认为这将不会是一个复杂的任务编程获取地址,但我的搜索引擎和StackOverflow的技能都上来了空。

在这一点上,我开始考虑做一个UDP广播/听环路听到我自己的要求和提取的地址,但真的看起来像一个hackey杂牌。 是否有一个API某处新的WinRT的东西,将让我去吗?

请注意,我说:“WinRT的应用程序,这意味着像典型的机制Dns.GetHostEntryNetworkInterface.GetAllInterfaces()是行不通的。

Answer 1:

多挖后,我发现你需要用信息NetworkInformation和主机名 。

NetworkInformation.GetInternetConnectionProfile检索与当前使用本地计算机的网络连接相关联的连接配置文件。

NetworkInformation.GetHostNames检索主机名的列表。 这不是很明显,但是这包括IPv4和IPv6地址的字符串。

使用这个信息,我们可以得到连接到这样的网络的网络适配器的IP地址:

public string CurrentIPAddress()
{
    var icp = NetworkInformation.GetInternetConnectionProfile();

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

        if (hostname != null)
        {
            // the ip address
            return hostname.CanonicalName;
        }
    }

    return string.Empty;
}

需要注意的是主机名具有性能CanonicalName,显示名称和RawName,但他们似乎都返回相同的字符串。

我们也可以得到类似这种代码多个适配器地址:

private IEnumerable<string> GetCurrentIpAddresses()
{
    var profiles = NetworkInformation.GetConnectionProfiles().ToList();

    // the Internet connection profile doesn't seem to be in the above list
    profiles.Add(NetworkInformation.GetInternetConnectionProfile());

    IEnumerable<HostName> hostnames =
        NetworkInformation.GetHostNames().Where(h => 
            h.IPInformation != null &&
            h.IPInformation.NetworkAdapter != null).ToList();

    return (from h in hostnames
            from p in profiles
            where h.IPInformation.NetworkAdapter.NetworkAdapterId ==
                  p.NetworkAdapter.NetworkAdapterId
            select string.Format("{0}, {1}", p.ProfileName, h.CanonicalName)).ToList();
}


Answer 2:

关于接受的答案,你只需要这样的:

HostName localHostName = NetworkInformation.GetHostNames().FirstOrDefault(h =>
                    h.IPInformation != null &&
                    h.IPInformation.NetworkAdapter != null);

你可以得到本地IP地址这种方式:

string ipAddress = localHostName.RawName; //XXX.XXX.XXX.XXX

命名空间中使用:

using System.Linq;
using Windows.Networking;
using Windows.Networking.Connectivity;


文章来源: Query Local IP Address