问题描述
我想找到机器的本地IP地址,然后在文本框中显示它.
我在.Net 4.0或正式的VB.Net中有很多代码片段,但是我无法将其放入Windows 8 Metro应用程序中.因为某些名称空间是在.Net Framework 4.5中移动或重命名的..
M使用Visual Basic(VB)和XAML在Windows 8 Pro上运行的Visual Studio 11(2012)中进行设计.
在此先感谢...
I want to find the local ip address of the machine and simply show it in the textbox.
I got lots of snippets in .Net 4.0 OR formal VB.Net, but i am not able to put it in windows 8 metro app. because some of the namespaces are moved or renamed in .Net Framework 4.5..
M using Visual Basic (VB) with XAML for designing in Visual Studio 11 (2012) running on Windows 8 Pro.
Thanks in advance...
推荐答案
public static string CurrentIPAddress()
{
var icp = NetworkInformation.GetInternetConnectionProfile();
if(icp != null && icp.NetworkAdapter != null)
{
var hostname =
NetworkInformation.GetHostNames().SingleOrDefault(
hn =>
hn.NetworkAdapter != null &&
hn.NetworkAdapter.NetworkAdapterId ==
icp.NetworkAdapter.NetworkAdapterId);
if(hostname != null)
{
// the ip address
return hostname.CanonicalName;
}
}
return string.Empty;
}
Note that HostName has properties CanonicalName, DisplayName and RawName, but they all seem to return the same string.
We can also get addresses for multiple adapters with code similar to this:
IEnumerable<connectionprofile> profiles =
NetworkInformation.GetConnectionProfiles().Where(
p => p.NetworkAdapter != null).ToList();
IEnumerable<hostname> hostnames =
NetworkInformation.GetHostNames().Where(h=>h.NetworkAdapter != null).ToList();
foreach (ConnectionProfile profile in profiles)
{
Debug.WriteLine(
"{0}, {1}",
profile.ProfileName,
hostnames.Single(hn =>
hn.NetworkAdapter.NetworkAdapterId ==
profile.NetworkAdapter.NetworkAdapterId).CanonicalName);
}
如果同时连接无线网络和有线网络,则在我的机器上会得到:
有线以太网连接,192.168.1.71
我的SSID 192.168.1.72
If I connect a wireless network as well as my wired network then on my machine I get:
Wired Ethernet Connection, 192.168.1.71
My SSID, 192.168.1.72
这篇关于如何在XAML中找到IP地址和MAC地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!