连接到蜂窝网络时获取Android的IP地址

Jun*_*tes 1 ip networking android

当通过移动数据网络连接到互联网时,有没有简单的方法来获取我的手机的IP地址.为了获得WiFi IP地址,我正在使用以下简单的技术.

 WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Run Code Online (Sandbox Code Playgroud)

有没有类似上面的方法来获取移动数据网络的IP地址.

我使用了以下代码,但它返回了MAC地址,WiFi和蜂窝网络的IP地址,但我只对蜂窝IP地址感兴趣.

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();
                                    Log.i("Sarao5",ipAddress);
                                }
                            }
                        }
                    } catch (SocketException ex) {}
Run Code Online (Sandbox Code Playgroud)

Rav*_*ari 7

使用我在我的应用程序中使用的以下代码 -

public static String getDeviceIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface networkInterface : networkInterfaces) {
            List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses());
            for (InetAddress inetAddress : inetAddresses) {
                if (!inetAddress.isLoopbackAddress()) {
                    String sAddr = inetAddress.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            // drop ip6 port suffix
                            int delim = sAddr.indexOf('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)

这是最简单的方法.

希望我的回答很有帮助.