Here you can find the source of getIPAddress(boolean useIPv4)
Parameter | Description |
---|---|
ipv4 | true=return ipv4, false=return ipv6 |
@SuppressLint("DefaultLocale") public static String getIPAddress(boolean useIPv4)
//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 ""; } }