Here you can find the source of getIPAddress(boolean useIPv4)
Parameter | Description |
---|---|
ipv4 | true=return ipv4, false=return ipv6 |
public static String getIPAddress(boolean useIPv4)
//package com.java2s; //License from project: Apache License import java.net.*; import java.util.*; public class Main { /**/*from w w w .java2 s . co m*/ * Get IP address from first non-localhost interface * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); if (addr instanceof Inet4Address) { if (useIPv4) return sAddr; } else { if (!useIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; } }