#挑战30天在头条写日记#
背景:用nginx做了负载,想知道哪些业务服务器是正常的。于是写了一个可以访问的接口,用来返回当前业务服务器的IP地址。
查了不少资料,有很多是这样写的:
使用InetAddress(实际测试,这个会返回 127.0.0.1)
InetAddress提供了获取本地主机信息的方法:
InetAddress.getLocalHost().getHostName(); //获取计算机名称
InetAddress.getLocalHost().getHostAddress(); //获取IP地址
正确的写法:
StringBuffer buf = new StringBuffer();
try {
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
Enumeration<InetAddress> address = nif.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress addr = address.nextElement();
if (addr instanceof Inet4Address) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append(addr.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
返回 buf.toString() 会得到类似 192.168.0.135,127.0.0.1 这样的结果。
如果有外网地址,应该也是可以获取的。
希望能帮助到有需要的小伙伴~!