我正在使用 xamarin 表單,但我遇到了一個問題,
我正在嘗試從 WIFI 獲取 DNS 服務器地址,并且我正在使用以下代碼:
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in networkInterfaces)
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
foreach (IPAddress dnsAdress in dnsAddresses)
{
Debug.WriteLine(dnsAdress);
}
}
}
問題是當我在 Microsoft Emulator“ UWP ”上使用此代碼時,一切正常,請參閱下面使用 UWP 設備的圖片
但是當我使用我的 android 手機時沒有任何效果,請參見下面 使用 android 設備的圖片
注意:所有設備都連接在同一個 wifi 上
uj5u.com熱心網友回復:
我做了一個簡單的測驗你的代碼并得到相同的空值。然后我閱讀了 IPInterfaceProperties.DnsAddresses 屬性檔案,似乎它不支持 xamarin.android。
您可以查看它:https ://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.ipinterfaceproperties.dnsaddresses?view=net-6.0
另外,我也搜索了這個但找不到任何解決方案。所以我嘗試使用android原生的方法來獲取dns地址,代碼如下。所以你可以嘗試使用依賴服務來獲取android的dns地址。
ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);
//NetworkInfo has been deprecated, but I can not find the new api to to this
NetworkInfo activeNetworkInfo = cm.ActiveNetworkInfo;
foreach (Network network in cm.GetAllNetworks())
{
NetworkInfo networkInfo = cm.GetNetworkInfo(network);
if (networkInfo.GetType() == activeNetworkInfo.GetType())
{
LinkProperties lp = cm.GetLinkProperties(network);
foreach (InetAddress addr in lp.DnsServers)
{
var a = addr.GetAddress();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470491.html
標籤:C# xamarin xamarin.forms xamarin.android
下一篇:xamarin導航登錄管理
