C# xamarin- How to get the ip address of the device

Viewed 959

I need to get the ipv4 address of the device without accessing external sites.

IPAddress[] LocalIp = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress iP in LocalIp)
{
    if (iP.AddressFamily == AddressFamily.InterNetwork)
    {
        MachineIP = iP;
    }
}

returns local IP but I need to know the public IP of the device on the 3G network and when connecting to wi-fi that of wi-fi. does anyone have any suggestions?

1 Answers

but I need to know the public IP of the device on the 3G network and when connecting to wi-fi that of wi-fi. does anyone have any suggestions?

If you would like to get the IP address of your device when connected to Wi-Fi, you can try following code:

Firstly, define interface in Form shared code.

 public interface IPAddressManager
{
    string GetIPAddress();
}

Getting ip address when device connected wifi in Android platform.

[assembly: Dependency(typeof(GetAddressManager))]
namespace demo3.Droid
{
 public  class GetAddressManager : IPAddressManager
{
    string ipAddress;
    public string GetIPAddress()
    {
        WifiManager wifiMgr = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
        WifiInfo wifiInfo = wifiMgr.ConnectionInfo;
        int ip = wifiInfo.IpAddress;
        ipAddress = Formatter.FormatIpAddress(ip);
        return ipAddress;
    }
}
}

Uisng DependencyService to get Ip Address.

 private void btn1_Clicked(object sender, EventArgs e)
    {
        string ip = DependencyService.Get<IPAddressManager>().GetIPAddress();
    }
Related