0

我是 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 地址的格式化程序一样的方法?我还想获得有关如何在其他 Internet 信息上实现相同效果的链接或指南。谢谢!

4

2 回答 2

0

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 文档缺少此信息。

于 2014-05-19T14:04:58.810 回答
0

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

于 2014-05-19T14:46:03.943 回答