java获取主机IP地址方法总结。
1.第一种方法,也是大家最常用的方法
InetAddress.getLocalHost().getHostAddress()
有些服务器上,这个方法得到的ip地址是127.0.0.1,但是,大多数服务器,都能够得到真实ip
只要是得到127的地址的,hosts文件的配置都是这样:
127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
而正常的服务器的hosts文件是:
127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6
172.18.130.39 slave2
所以,现在都是在那些服务器上,设置host name的解析的ip地址。
2.第二种方法通过NetworkInterface获取,在linux服务器上都可以获取IP地址
[html] view plaincopy在CODE上查看代码片派生到我的代码片
StringBuilder IFCONFIG=new StringBuilder();
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString()+”");
}
}
}
} catch (SocketException ex) {
}
System.out.println(IFCONFIG);