Xamarin.Android DhcpInfo.Netmask returns 0

余生长醉 提交于 2019-12-24 21:24:00

问题


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);



        };

    }
}

}


回答1:


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);
}


来源:https://stackoverflow.com/questions/45697233/xamarin-android-dhcpinfo-netmask-returns-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!