Skip to content

Commit

Permalink
0000784: Use the NetworkInterface Java class to get the current ipAdd…
Browse files Browse the repository at this point in the history
…ress of a node
  • Loading branch information
chenson42 committed Aug 26, 2012
1 parent e7262b9 commit 79cb75d
Showing 1 changed file with 36 additions and 8 deletions.
Expand Up @@ -23,8 +23,13 @@
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

Expand All @@ -40,7 +45,7 @@
* General application utility methods
*/
public class AppUtils {

private static String UNKNOWN = "unknown";

private static Logger log = LoggerFactory.getLogger(AppUtils.class);
Expand Down Expand Up @@ -78,7 +83,7 @@ public static String getHostName() {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (Exception ex) {
log.warn(ex.getMessage(),ex);
log.warn(ex.getMessage(), ex);
}
}
return hostName;
Expand All @@ -88,9 +93,32 @@ public static String getIpAddress() {
String ipAddress = System.getProperty("ip.address", UNKNOWN);
if (UNKNOWN.equals(ipAddress)) {
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface networkInterface = null;
while (interfaces.hasMoreElements()) {
networkInterface = interfaces.nextElement();
if (!networkInterface.isLoopback() && networkInterface.isUp()) {
List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : addresses) {
if (!interfaceAddress.getAddress().isLoopbackAddress()) {
ipAddress = interfaceAddress.getAddress().getHostAddress();
}
}
}

}
} catch (Exception ex) {
log.warn(ex.getMessage(),ex);
log.warn(ex.getMessage(), ex);
} finally {
}
}

if (UNKNOWN.equals(ipAddress)) {
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
log.warn(ex.getMessage(), ex);
ipAddress = "127.0.0.1";
}
}
return ipAddress;
Expand Down Expand Up @@ -162,11 +190,12 @@ public static void runBsh(Map<String, Object> variables, String script) {
throw new RuntimeException(e);
}
}

/**
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*
* @param port
* the port to check for availability
*/
public static boolean isPortAvailable(int port) {
if (port < 1 || port > 65535) {
Expand Down Expand Up @@ -198,6 +227,5 @@ public static boolean isPortAvailable(int port) {

return false;
}


}

0 comments on commit 79cb75d

Please sign in to comment.