Skip to content

Instantly share code, notes, and snippets.

@jmruc
Forked from gospodinbodurov/gist:3697021
Created September 11, 2012 10:47
Show Gist options
  • Save jmruc/3697547 to your computer and use it in GitHub Desktop.
Save jmruc/3697547 to your computer and use it in GitHub Desktop.
import java.net.*;
import java.util.*;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class InetAddressTest
{
private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
public static InetAddress getCurrentEnvironmentNetworkIp() {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
}
List<InetAddress> addresses = new ArrayList<InetAddress>();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress addr = address.nextElement();
if(Pattern.compile(IPADDRESS_PATTERN).matcher(addr.getHostAddress()).matches() && !addr.isLoopbackAddress()) {
addresses.add(addr);
}
}
}
try {
InetAddress localHost = InetAddress.getLocalHost();
if (addresses.contains(localHost))
{
return localHost;
}
} catch(Exception e) {
return null;
}
if(addresses.size() == 0) {
return null;
}
return addresses.get(0);
}
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
System.out.println(getCurrentEnvironmentNetworkIp());
System.out.println(Address.getCanonicalHostName());
System.out.println(getCurrentEnvironmentNetworkIp().getCanonicalHostName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment