Created
September 24, 2014 09:32
-
-
Save xxnjdlys/842e867b1abc73be43f9 to your computer and use it in GitHub Desktop.
getIPAddress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get IP address from first non-localhost interface | |
* @param useIPv4 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(); | |
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); | |
if (useIPv4) { | |
if (isIPv4) | |
return sAddr; | |
} else { | |
if (!isIPv4) { | |
int delim = sAddr.indexOf('%'); // drop ip6 port suffix | |
return delim<0 ? sAddr : sAddr.substring(0, delim); | |
} | |
} | |
} | |
} | |
} | |
} catch (Exception ignore) { } // for now eat exceptions | |
return ""; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment