public static String[] getAllLocalIP() {
String[] localServers = null;
try {
InetAddress addr = InetAddress.getLocalHost();
String hostName = addr.getHostName().toString();
// 获取本机ip
InetAddress[] ipsAddr = InetAddress.getAllByName(hostName);
localServers = new String[ipsAddr.length];
for (int i = 0; i < ipsAddr.length; i++) {
if (ipsAddr[i] != null) {
localServers[i] = ipsAddr[i].getHostAddress().toString();
}
}
} catch (Exception e) {
}
return localServers;
}
这种方法在Windows下是没问题的,但是在Linux下运行的时候很有可能会是127.0.0.1,修改host虽然可以解决,但并不是个明智之举。下面这种方法在Windows和Linux下都可以获得正确的IP: