以可读形式获取IP地址的android代码

时间:2012-06-11 18:06:47

标签: android ip

我是Android开发的新手,我正在做一个应用程序,它通过短信将一个Android设备的IP地址发送到另一个。我需要获得十进制的IP,如192.168.0.4,而不是十六进制,这是我从下面的代码得到的。任何想法如何做到这一点,并感谢你的帮助。

    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();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();

                    }
                 }
             }
         } catch (SocketException ex) {
             Log.e(TAG, ex.toString());
         }

         return null;
    } 

4 个答案:

答案 0 :(得分:8)

public static String getLocalIpv4Address(){
    try {
        String ipv4;
        List<NetworkInterface>  nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
        if(nilist.size() > 0){
            for (NetworkInterface ni: nilist){
                List<InetAddress>  ialist = Collections.list(ni.getInetAddresses());
                if(ialist.size()>0){
                    for (InetAddress address: ialist){
                        if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress())){ 
                            return ipv4;
                        }
                    }
                }

            }
        }

    } catch (SocketException ex) {

    }
    return "";
}

这可以吗?只有可用时,此函数才会返回ipv4(xxx.xxx.xxx.xxx模式)。

请注意,您提到的那些十六进制值应该是ipv6地址。

答案 1 :(得分:3)

This post解释了如何获取设备的IP。

这段代码(取自上述帖子)应该以正确的方式为您提供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();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

答案 2 :(得分:0)

虽然我的答案是正确的,但我发现如果我循环通过特定设备“wlan0”的ip_addresses,第一个地址是ipv6,第二个地址是ipv4。我只返回第一个值,这就是为什么我只得到一个十六进制字符串。

for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                String ip_address = inetAddress.getHostAddress();
                Log.d(APP_NAME, "IP: " + ip_address);
                //return if_name + ": " + ip_address;
}

注意我注释掉了“return”

答案 3 :(得分:-1)

可以使用getprop命令从shell获取此信息。