Android IP Address Get getIPAddress(boolean useIPv4)

Here you can find the source of getIPAddress(boolean useIPv4)

Description

Get IP address from first non-localhost interface

Parameter

Parameter Description
ipv4 true=return ipv4, false=return ipv6

Return

address or empty string

Declaration

@SuppressLint("DefaultLocale")
public static String getIPAddress(boolean useIPv4) 

Method Source Code

//package com.java2s;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;
import android.annotation.SuppressLint;

public class Main {
    /**//from   w  w  w  . ja  v a  2s  . co m
     * Get IP address from first non-localhost interface
     * 
     * @param ipv4
     *            true=return ipv4, false=return ipv6
     * @return address or empty string
     */
    @SuppressLint("DefaultLocale")
    public static String getIPAddress(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 "";
    }
}

Related

  1. getInetIpAddress()
  2. getLocalIpAddress()
  3. getIPAddress(boolean useIPv4)
  4. getHostAddress(int address)
  5. getLocalHostAddress()
  6. getTargetInetaddress(String target)
  7. getDevicesMac(Context context)
  8. getDevicesIP(Context context)
  9. getIPs()