Skip to content

Instantly share code, notes, and snippets.

@gospodinbodurov
Created September 11, 2012 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gospodinbodurov/3697021 to your computer and use it in GitHub Desktop.
Save gospodinbodurov/3697021 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 {
for (InetAddress addr : addresses) {
if(addr.getHostAddress().equals(InetAddress.getLocalHost().getHostAddress())) {
return InetAddress.getLocalHost();
}
}
} 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