'Xamarin Forms Get Device Ip address
I'm working with a Xamarin.Forms cross-platform app. Now, I need to obtain the device home Ip (I mean the static one). Which is the simplest way to get the IPv4 address of the device in Xamarin.Forms?
Solution 1:[1]
You can use Dns.GetHostAddresses which is under using System.Net
Call this function
var ip = GetLocalAddress();
GetLocalAddress:
private string GetLocalAddress()
{
var IpAddress = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault();
if (IpAddress != null)
return IpAddress.ToString();
return "Could not locate IP Address";
}
Solution 2:[2]
You can use DependencyService to get Ip address, then following code is Android project. For other Platform, you can take a look:
class IPAddressManager : IIPAddressManager
{
public string GetIPAddress()
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
if (addresses?[0] != null)
{
return addresses[0].ToString();
}
else
{
return null;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Brandon Minnick |
| Solution 2 | Aazarus |
