Android 如何获得 IPV4 格式的 IP_ADDRESS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11015912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:44:50  来源:igfitidea点击:

How do I get IP_ADDRESS in IPV4 format

androidip-addressandroid-4.0-ice-cream-sandwichandroid-networking

提问by Rahul Baradia

I am trying to get the IP address of an device i.e using WIFI or 3G connection. I am getting the ip address in IPV6 format which is not understandable. I want in IPV4 format IP address.I have done google but dint found any proper solutions.

我正在尝试获取设备的 IP 地址,即使用 WIFI 或 3G 连接。我正在获取 IPV6 格式的 IP 地址,这是无法理解的。我想要 IPV4 格式的 IP 地址。我已经做了谷歌,但没有找到任何合适的解决方案。

here is code which I am using to get IP address of an device

这是我用来获取设备 IP 地址的代码

public String getLocalIpAddress() {
    try {
        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();
                System.out.println("ip1--:" + inetAddress);
                System.out.println("ip2--:" + inetAddress.getHostAddress());
                if (!inetAddress.isLoopbackAddress()) {


                    String ip = inetAddress.getHostAddress().toString();
                    System.out.println("ip---::" + ip);
                    EditText tv = (EditText) findViewById(R.id.ipadd);
                    tv.setText(ip);
                    return inetAddress.getHostAddress().toString();

                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

I am getting this ouput :

我得到这个输出:

ip1--:/fe80::5054:ff:fe12:3456%eth0%2
ip2--:fe80::5054:ff:fe12:3456%eth0

It should be displayed like this :

它应该显示如下:

192.168.1.1

please help me out..

请帮帮我..

回答by Rahul Baradia

After trying many tricks.. finally I can get the IP address in IPV4 format.. Here is my code..

尝试了很多技巧后..终于我可以得到IPV4格式的IP地址..这是我的代码..

public String getLocalIpAddress() {
    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();
                System.out.println("ip1--:" + inetAddress);
                System.out.println("ip2--:" + inetAddress.getHostAddress());

      // for getting IPV4 format
      if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {

                    String ip = inetAddress.getHostAddress().toString();
                    System.out.println("ip---::" + ip);
                    EditText tv = (EditText) findViewById(R.id.ipadd);
                    tv.setText(ip);
                    // return inetAddress.getHostAddress().toString();
                    return ip;
                }
            }
        }
    } catch (Exception ex) {
        Log.e("IP Address", ex.toString());
    }
    return null;
}

Added ifcondition as shown below

添加if条件如下所示

 /**This shows IPV4 format IP address*/
 if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())){}

instead of this

而不是这个

 /**This shows IPV6 format IP address*/
 if (!inetAddress.isLoopbackAddress()){}

Many Thanks.. Rahul

非常感谢..拉胡尔

An alternative for checking if the address is a version 4 address is:

检查地址是否为版本 4 地址的替代方法是:

if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)

回答by Simon Hewison

You cannot assume that any device has just one network address. You also cannot assume that it will have any IPv4 - it may be IPv6 only, so your application will need to be able to handle both IPv4 and IPv6 address displays.

您不能假设任何设备只有一个网络地址。您也不能假设它将具有任何 IPv4 - 它可能只是 IPv6,因此您的应用程序需要能够处理 IPv4 和 IPv6 地址显示。

Typically, an Android phone has at least two interfaces that get assigned usable ip addresses, rmnet0 for the 3G data, which for IPv4 is often carrier-grade NATed and so cannot accept incoming socket connections, and may also have an IPv6 address; and wlan0 for the wifi, which will have whatever IPv4 and/or IPv6 address it can negotiate with the network it attaches to.

通常,Android 手机至少有两个接口可以分配可用的 ip 地址,rmnet0 用于 3G 数据,对于 IPv4,它通常是运营商级的 NAT,因此不能接受传入的套接字连接,并且可能还有一个 IPv6 地址;和 wlan0 用​​于 wifi,它将具有它可以与其连接的网络协商的任何 IPv4 和/或 IPv6 地址。

Some versions of Android will intentionally drop the (typically more expensive) rmnet0 link when it attaches to wifi - in an attempt to reduce 3G data usage. This behaviour is a problem when the wifi has attached to something that is a captive portal that requires a manual sign-in.

某些版本的 Android 在连接到 wifi 时会故意丢弃(通常更昂贵)rmnet0 链接 - 以尝试减少 3G 数据使用。当 wifi 连接到需要手动登录的强制门户时,此行为是一个问题。

回答by 0nyx

It seems there is a seperate class Inet4Addressin the Java API for IPv4 addresses.

似乎在用于 IPv4 地址的 Java API 中有一个单独的类Inet4Address

回答by rkachach

Following is a simple way to check either if it's IPv4 or IPv6:

以下是检查它是 IPv4 还是 IPv6 的简单方法:

InetAddress address = InetAddress.getByName(ip);
if (address instanceof Inet6Address) {
    // It's ipv6
} else if (address instanceof Inet4Address) {
    // It's ipv4
}