Search code examples
c#xamarinxamarin.formsxamarin.iossystem.net

How to get Local Router Address[Not IPV4 address of device] in Xamarin


I have tried below code but it keeps on giving the me iPhone(ie.Device) IP Address. But I want to get a ROUTER IP ADDRESS

public string GetIPAddress()
    {
        String ipAddress = "";

        foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
        {
            Console.WriteLine(netInterface);
            if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
            {
                foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
                {
                    if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ipAddress = addrInfo.Address.ToString();
                    }
                }
            }
        }

iPhone IPAddress: 192.168.0.19 Router: 192.168.0.1

Wifi address config screen

I can do the Hacky way of removing the '9' from the last set of IP address. But I don't want to do this.


Solution

  • You can use the following code to get a ROUTER IP ADDRESS(Gateway address) from Android side.

    Create a DependenceService in Forms folder.

    public interface INetServices  
    {  
        string ConvertGateway();  
    } 
    

    Then achieve this interface in the android folder.

    [assembly: Dependency(typeof(NetService))]  
       namespace Forms.Droid  
       {  
           class NetService: INetServices  
           {  
               [Obsolete]
               public string ConvertGateway()  
               {  
                   WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);  
                   int ip = wifiManager.ConnectionInfo.IpAddress;  
                   int gateway = wifiManager.DhcpInfo.Gateway;
    
                   IPAddress ipAddr = new IPAddress(ip);  
                   IPAddress gatewayAddr = new IPAddress(gateway);
                  
                  
                   return gatewayAddr.ToString();  
               }  
           }  
       }  
    

    And add following permission in the AndroidManifest.xml

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

    In the Xamarin forms, you can get ROUTER IP ADDRESS like following code.

    var gatewayAddress = DependencyService.Get<INetServices>().ConvertGateway();            
    Console.WriteLine(gatewayAddress);