我需要知道我的实际本地IP地址(即不是环回地址)从一个Windows8WinRT/应用程序。我需要这个有几个原因。最简单的是,在应用程序的UI中,我想显示一些文本,比如“您的本地网络IP地址是:从代码中查询的IP”。
我们还为一些额外的网络通信使用该地址。这些通信是完全有效的,因为如果我查看控制面板中的IP地址,然后将其硬编码到应用程序中,所有通信都能工作。让对话框中的用户去查看地址并手动输入,这是我真的非常非常想避免的事情。
我认为以编程方式获取地址并不是一项复杂的任务,但我的搜索引擎和StackOverflow技能正在变得空洞无物。
此时,我开始考虑执行一个UDP广播/听循环,以听到我自己的请求并从中提取地址,但这看起来确实是一个hackey假象。在新的WinRT中有什么API能让我达到这个目的吗?
请注意,我说的是"WinRT应用程序,这意味着典型的机制,如Dns.GetHostEntry或NetworkInterface.GetAllInterfaces()将无法工作。“
发布于 2012-05-04 22:12:25
经过深入研究,我找到了使用NetworkInformation和HostName需要的信息。
NetworkInformation.GetInternetConnectionProfile检索与本地计算机当前使用的internet连接相关联的连接配置文件。
NetworkInformation.GetHostNames检索主机名列表。这并不明显,但这包括IPv4和IPv6地址作为字符串。
使用这些信息,我们可以获得连接到internet的网络适配器的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;
}请注意,HostName具有属性CanonicalName、DisplayName和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();
}发布于 2015-02-08 21:28:04
关于公认的答案,你只需要这样:
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;https://stackoverflow.com/questions/10336521
复制相似问题