Getting IP address in a readable form android code

后端 未结 4 972
囚心锁ツ
囚心锁ツ 2021-01-26 04:31

I am new to android development and I am doing an application which sends the IP address of an android device to another one by sms. I need to get the IP in decimal like this 19

4条回答
  •  被撕碎了的回忆
    2021-01-26 05:01

    public static String getLocalIpv4Address(){
        try {
            String ipv4;
            List  nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            if(nilist.size() > 0){
                for (NetworkInterface ni: nilist){
                    List  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 "";
    }
    

    Should this be ok ? This function will return ipv4 (in xxx.xxx.xxx.xxx pattern) only if available.

    Please note that those hexadecimal value you mentioned should be an ipv6 address.

提交回复
热议问题