【问题标题】:Android - How to format Internet properties from Dhcp?Android - 如何从 Dhcp 格式化 Internet 属性?
【发布时间】:2014-05-19 13:47:15
【问题描述】:

我是 android 新手,我正在创建一个应用程序,其中显示 LAN IP 地址、子网掩码、默认网关和其他信息我使用以下代码获得 IP 地址

try{
    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wi = wm.getConnectionInfo();
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    TextView ipAddressText = (TextView)findViewById(R.id.productInfo_lanIpAddress);
    ipAddressText.setText(ip);
    DhcpInfo dInfo = wm.getDhcpInfo();

    ip = String.valueOf(dInfo.gateway);
    TextView defaultGateway = (TextView)findViewById(R.id.productInfo_defaultGateway);
        defaultGateway.setText(ip);
    }//*/
    catch (Exception ex) {
        TextView ipAddressText = (TextView)findViewById(R.id.productInfo_lanIpAddress);
        ipAddressText.setText(ex.toString());

    }
    /*

现在我相信我得到了默认网关,但它是数字格式的,所以它不能正确显示(我得到 16885352)有没有像我们用来格式化 IP 地址的 Formatter 一样的方法? 我还想获得有关如何在其他 Internet 信息上实现相同效果的链接或指南。 谢谢!

【问题讨论】:

    标签: android android-wifi android-internet android-wireless


    【解决方案1】:

    getIpAddress 方法返回 IP 的 int 表示形式。例如以下ip: 172.16.254.1 是二进制的

    10101100 00010000 11111110 00000001
      172      16       254        1
    

    所以等效的 int 是 2886794753。 要将其转换为 IP 地址的字符串表示形式,您可以使用以下内容:

    public String intToIp(int i) {
        return ((i >> 24 ) & 0xFF ) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ( i & 0xFF) ;
    }
    

    android 文档缺少此信息。

    【讨论】:

      【解决方案2】:

      好的,所以我找到了一种方法来实现它,它与我们获取 IP 地址的方式类似。 即,使用 Formatter.formatIpAddress() 获取正确的子网掩码、默认网关、主 DNS 和辅助 DNS。 想通了,因为它们的格式相同。 干杯!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多