编程技术分享平台

网站首页 > 技术教程 正文

JAVA获取运行服务器IP地址的正确写法

xnh888 2024-10-17 17:11:54 技术教程 20 ℃ 0 评论

#挑战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 这样的结果。

如果有外网地址,应该也是可以获取的。

希望能帮助到有需要的小伙伴~!

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表