How do I get IP_ADDRESS in IPV4 format

前端 未结 4 1623
独厮守ぢ
独厮守ぢ 2020-12-04 19:55

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

4条回答
  •  天命终不由人
    2020-12-04 20:45

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

    public String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration 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 if condition as shown below

     /**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:

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

提交回复
热议问题