Retrieve IP address of device

2019-07-06 05:06发布

I am using Xamarin.Android and wrote the following code:

public TextView text;
text = FindViewById<TextView>(Resource.Id.viewIP);
foreach (IPAddress adress in Dns.GetHostAddresses(Dns.GetHostName()))
{
    text.Text = "IP Adress: " + adress;
}

However, when I open the application it shuts down immediately. Am I using the correct way of getting the IP address' of the device?

4条回答
Anthone
2楼-- · 2019-07-06 05:31

For me this worked in 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楼-- · 2019-07-06 05:35

All the answers I've seen to this question have only gotten the internal IP address of my device while on my home network (198.162.#.#). So I took a slightly different approach, and ask the internet more directly. ipify.org has a nice and simple endpoint for getting your IP address, that can be executed in your shared code. For example...

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;

Where "IpResult" is a POCO with a single string property named "Ip" (that you need to create, in addition to this code.)

查看更多
甜甜的少女心
4楼-- · 2019-07-06 05:38

From the Xamarin forums

Java.Util.IEnumeration networkInterfaces = NetworkInterface.NetworkInterfaces;

while(networkInterfaces.HasMoreElements)
{
  Java.Net.NetworkInterface netInterface = 
                            (Java.Net.NetworkInterface)networkInterfaces.NextElement();
  Console.WriteLine(netInterface.ToString());
}
查看更多
等我变得足够好
5楼-- · 2019-07-06 05:57

added to mainifest:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

for get local 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!");
}

See this answer : https://stackoverflow.com/a/6803109/4349342

查看更多
登录 后发表回答