Ramy Lerner
Ramy Lerner

Reputation: 7

Xamarin.Android DhcpInfo.Netmask returns 0

I'm trying to get my network address with DhcpInfo.Netmask but the net mask I get is 0, even though my device is connected to a wifi network. This is the code I'm using:

namespace checks
{
[Activity(Label = "checks", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView (Resource.Layout.Main);

        Button dataButton = FindViewById<Button>(Resource.Id.connectionDataButton);

        dataButton.Click += (object sender, EventArgs e) =>
        {

            WifiManager wifiManager = (WifiManager)GetSystemService(Context.WifiService);
            var d = wifiManager.DhcpInfo;

            Console.WriteLine("My Net mask: {0}", d.Netmask);



        };

    }
}

}

Upvotes: 0

Views: 873

Answers (1)

Elvis Xia - MSFT
Elvis Xia - MSFT

Reputation: 10831

I'm trying to get my network address with DhcpInfo.Netmask but the net mask I get is 0, even though my device is connected to a wifi network.

This is a Known Issue.

As a workaround, you can use the following codes to get the NetworkPrefixLength and convert it to NetMask by this table:

WifiManager wifiManager = (WifiManager)GetSystemService(Context.WifiService);
DhcpInfo dhcpInfo = wifiManager.DhcpInfo;
try
{
    byte[] ipAddress = BitConverter.GetBytes(dhcpInfo.IpAddress);
    InetAddress inetAddress = InetAddress.GetByAddress(ipAddress);
    NetworkInterface networkInterface = NetworkInterface.GetByInetAddress(inetAddress);
    foreach (InterfaceAddress address in networkInterface.InterfaceAddresses)
    {
        //short netPrefix = address.getNetworkPrefixLength(); 
        //Log.d(TAG, address.toString());
        var prefix=address.NetworkPrefixLength;
    }
}
catch (IOException exception)
{
    Log.Debug("Exception:", exception.Message);
}

Upvotes: 1

Related Questions