Last active
May 10, 2019 02:30
-
-
Save kribblo/daa9dfc42ee26af37626efb831a9fad0 to your computer and use it in GitHub Desktop.
Get site local ip in Java, skipping loopback, docker etc
This file contains 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
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