网站首页 > 技术教程 正文
背景:用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 这样的结果。
如果有外网地址,应该也是可以获取的。
希望能帮助到有需要的小伙伴~!
猜你喜欢
- 2024-10-17 负载均衡获得真实源IP的6种方法(负载均衡 源地址转换)
- 2024-10-17 哎,我早就料到你获取IP地址的姿势不对啦!
- 2024-10-17 如何配置内网IP SSL证书?怎么将IP根证书导入客户端?
- 2024-10-17 三步实现IP地址HTTPS访问(三步打造ip)
- 2024-10-17 IP地址SSL证书获取流程(ssl设备的地址怎么查)
- 2024-10-17 从Apache apisix日志中获取客户端ip
- 2024-10-17 IP地址证书申请教程——六步实现https
- 2024-10-17 爬虫获取代理IP,满足不同的抓取需求
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 下划线是什么 (87)
- 精美网站 (58)
- qq登录界面 (90)
- nginx 命令 (82)
- nginx .http (73)
- nginx lua (70)
- nginx 重定向 (68)
- Nginx超时 (65)
- nginx 监控 (57)
- odbc (59)
- rar密码破解工具 (62)
- annotation (71)
- 红黑树 (57)
- 智力题 (62)
- php空间申请 (61)
- 按键精灵 注册码 (69)
- 软件测试报告 (59)
- ntcreatefile (64)
- 闪动文字 (56)
- guid (66)
- abap (63)
- mpeg 2 (65)
- column (63)
- dreamweaver教程 (57)
- excel行列转换 (56)
本文暂时没有评论,来添加一个吧(●'◡'●)