【问题标题】:find local network address in Android - including IP and NetMask? (ethernet not wifi)在 Android 中查找本地网络地址 - 包括 IP 和 NetMask? (以太网不是wifi)
【发布时间】:2014-10-20 18:54:45
【问题描述】:

在Android模拟器中,地址(eth0)是10.0.2.15/24

在支持以太网的平板电脑上,eth0 具有相似的地址:例如192.168.0.2/24

如何通过现有的 Android API 找到它? (现有版本 - Android L 预览版之前!)。

我知道它可以通过 WifiManager.getDhcpInfo() 为 WiFi 完成 - 但我对 以太网 感兴趣 - 甚至更好的是 通用 方式。

【问题讨论】:

    标签: android networking ip-address mask ethernet


    【解决方案1】:

    这是一个获取掩码的方法,也就是网络前缀长度。最低 API 为 9,并且需要 INTERNET 权限。该地址有一个“/”前缀,但可以通过添加.toString.substring(1) 等轻松删除。

    public void logLocalIpAddresses() {
        Enumeration<NetworkInterface> nwis;
        try {
            nwis = NetworkInterface.getNetworkInterfaces();
            while (nwis.hasMoreElements()) {
    
                NetworkInterface ni = nwis.nextElement();
                for (InterfaceAddress ia : ni.getInterfaceAddresses())
    
                    Log.i(TAG, String.format("%s: %s/%d", 
                          ni.getDisplayName(), ia.getAddress(), ia.getNetworkPrefixLength()));
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • 我需要 API 8,但我想这可以。干杯!
    • > API 9 没问题,因为无论如何都开始在 API 11 中使用以太网!
    猜你喜欢
    • 2017-05-14
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 2014-09-22
    • 2019-02-03
    • 2012-01-25
    • 1970-01-01
    相关资源
    最近更新 更多