我正在使用Xamarin.Android并编写以下代码:
public TextView text;
text = FindViewById<TextView>(Resource.Id.viewIP);
foreach (IPAddress adress in Dns.GetHostAddresses(Dns.GetHostName()))
{
text.Text = "IP Adress: " + adress;
}
然而,当我打开应用程序时,它会立即关闭。我使用正确的方法来获取设备的IP地址吗?
答案 0 :(得分:5)
Java.Util.IEnumeration networkInterfaces = NetworkInterface.NetworkInterfaces;
while(networkInterfaces.HasMoreElements)
{
Java.Net.NetworkInterface netInterface =
(Java.Net.NetworkInterface)networkInterfaces.NextElement();
Console.WriteLine(netInterface.ToString());
}
答案 1 :(得分:2)
添加到mainifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
获取本地IP:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
答案 2 :(得分:0)
对我而言,这适用于PCL Xamarin:
public static string GetIPAddress()
{
var AllNetworkInterfaces = Collections.List(Java.Net.NetworkInterface.NetworkInterfaces);
var IPAddres = "";
foreach (var interfaces in AllNetworkInterfaces)
{
if (!(interfaces as Java.Net.NetworkInterface).Name.Contains("eth0")) continue;
var AddressInterface = (interfaces as Java.Net.NetworkInterface).InterfaceAddresses;
foreach (var AInterface in AddressInterface)
{
if(AInterface.Broadcast != null)
IPAddres = AInterface.Address.HostAddress;
}
}
return IPAddres;
}
答案 3 :(得分:0)
我在这个问题上看到的所有答案都只是在我的家庭网络上获得了我的设备的内部IP地址(198.162。#。#)。所以我采取了略微不同的方法,并更直接地询问互联网。 ipify.org有一个很好的简单端点来获取你的IP地址,可以在你的共享代码中执行。例如......
var client = new HttpClient();
var response = await client.GetAsync("https://api.ipify.org/?format=json");
var resultString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<IpResult>(resultString);
var yourIp = result.Ip;
其中“IpResult”是一个POCO,其中包含一个名为“Ip”的字符串属性(除此代码外,您还需要创建)。