如何在Win 10 UWP项目中找到本地IP地址 [英] How do I find the local IP address on a Win 10 UWP project
本文介绍了如何在Win 10 UWP项目中找到本地IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在尝试将管理控制台应用程序移植到Win 10 UWP应用程序。我在使用以下控制台代码中的System.Net.Dns时遇到问题。
I am currently trying to port an administrative console application over to a Win 10 UWP app. I am having trouble with using the System.Net.Dns from the following console code.
如何获取设备IP
以下是我尝试移植的控制台应用程序代码。
Here is the console app code that I am trying to port over.
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;
}
推荐答案
您可以尝试这样:
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;
}
上面的答案也是正确的
这篇关于如何在Win 10 UWP项目中找到本地IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文