0

您好我正在使用下面的代码来获取 android 设备的 IP 地址,

private String returnIPAdrress()
        {
            String IPAddress = null;
            try
                {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
                        {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                                {
                                    InetAddress inetAddress = enumIpAddr.nextElement();
                                    if (!inetAddress.isLoopbackAddress())
                                        {
                                            IPAddress = inetAddress.getHostAddress().toString();
                                        }
                                }
                        }

                }
            catch (SocketException ex)
                {
                    Log.e("ServerActivity", ex.toString());
                    return null;
                }
            return IPAddress;
        }

当我在 Galaxy 平板电脑(os=2.3)上测试它时,它工作正常并给了我有效的 IP 地址。

我已经在模拟器(os=2.2)上对其进行了测试,它给我的 IP 地址为10.0.2.15,我猜这也是有效的。

但是当在 Micromax canvas(os=4.1) 上运行它时,它给我的 IP 地址为 fe80::d0b3:3fff:fe9d:f68c%p2p0,这是错误的。

是因为操作系统版本不同吗?

我该如何解决这个问题?

4

2 回答 2

3

试试这个方法:

public static String getIPAddress() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (isIPv4 && intf.getDisplayName().startsWith("wlan")) {
                        return sAddr;
                    }
                }
            }
        }
    } catch (Exception ex) {
        return null;
    }
    return null;
}
于 2013-07-18T11:53:28.807 回答
1

您可以使用访问设备的 IP 地址dhcp.ipaddress

private final WifiManager manager;
private final DhcpInfo dhcp;     
private InetAddress getMyIP() {
    manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    dhcp = manager.getDhcpInfo();
    final String address = Formatter.formatIpAddress(dhcp.ipAddress); // ipAddress - IP address of my device, assigned through dhcp
    InetAddress myIP = null;

    try {
        myIP = InetAddress.getByName(address);

        Log.i("My IP  "," + myIP.toString());
    } catch (Exception e) {
        Log.e("Cannot find my own IP. Error ", e.toString());
    }

    return myIP;
}
于 2018-10-03T13:34:58.607 回答