Skip to content

Instantly share code, notes, and snippets.

@kribblo
Last active May 10, 2019 02:30
Show Gist options
  • Save kribblo/daa9dfc42ee26af37626efb831a9fad0 to your computer and use it in GitHub Desktop.
Save kribblo/daa9dfc42ee26af37626efb831a9fad0 to your computer and use it in GitHub Desktop.
Get site local ip in Java, skipping loopback, docker etc
package io.github.kribblo.ip;
import java.net.*;
import java.util.Collections;
public class SiteLocalIp {
public static String getSiteLocalIp() throws SocketException, UnknownHostException {
return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
.filter(SiteLocalIp::isValidInterface)
.flatMap(i -> Collections.list(i.getInetAddresses()).stream())
.filter(ip -> ip instanceof Inet4Address && ip.isSiteLocalAddress())
.findFirst().orElse(InetAddress.getLocalHost())
.getHostAddress();
}
private static boolean isValidInterface(NetworkInterface networkInterface) {
try {
return networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback();
} catch(SocketException e) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment