应用程序服务器由Windows环境整体迁移到Linux环境,出现了不能获取本机IP地址的问题
原因是下面一段JAVA代码在Linux下直接返回127.0.0.1。Windows下有效的InetAddress貌似在linux下不起作用。
public static String getLocalIP() {
String ip = "";
try {
InetAddress address = InetAddress.getLocalHost();
if(address != null) {
ip = address.getHostAddress();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
原因在于Java使用的JNI代码调用的是Linux中的gethostname内核函数
这个函数在Linux主机没有绑定IP的情况下根据Host文件定义返回默认的localhost或者127.0.0.1。
后改为改用NetworkInterface方式获取,可以取得IP地址。
public static String getLocalIP() {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
return "";
}
最后考虑到多块网卡问题,需要对多个NetworkInterface进行遍历,这里只取IPV4的IP地址
public static List getLocalIPList() {
List ipList = new ArrayList();
try {
Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface networkInterface;
Enumeration inetAddresses;
InetAddress inetAddress;
String ip;
while (networkInterfaces.hasMoreElements()) {
networkInterface = networkInterfaces.nextElement();
inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
inetAddress = inetAddresses.nextElement();
if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
ip = inetAddress.getHostAddress();
ipList.add(ip);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ipList;
}
参考
http://www.linuxidc.com/Linux/2012-12/75498.htm
https://my.oschina.net/zhongwenhao/blog/307879
http://www.blogjava.net/icewee/archive/2013/07/19/401739.html