简体   繁体   中英

No GatewayAddresses when looping through NetworkInterfaces on Xamarin.Android

I'm trying to scan the local IP address of a mobile device to ping all other devices in a network and discover local IP addresses. In the first step I'm retrieving the GatewayAddress of the local NetworkInterface like this:

foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
{
    if (f.OperationalStatus == OperationalStatus.Up)
    {
        foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
        {
            ip = d.Address.ToString();
        }
    }
}

This works perfectly fine on iOS, however on Android the GatewayAdresses have a count of 0 . As far as my research goes there has been bugs with NetworkInterface s in Xamarin but they seem to be all fixed by now.

You could use the code to get the ipv6 and ipv4.

 foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (f.OperationalStatus == OperationalStatus.Up)
            {
                //foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
                //{
                //    var ip = d.Address.ToString();
                //}
                IPAddress ipv6Address = f.GetIPProperties().UnicastAddresses[0].Address; //This will give ipv6 address of certain adapter
                IPAddress ipv4Address = f.GetIPProperties().UnicastAddresses[1].Address; //This will give ipv4 address of certain adapter

            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM