获取ip的第一反应就是:使用InetAddress这个类:方法如下
InetAddress.getLocalHost().getHostAddress();
public static void main(String[] args) {
try {
//用 getLocalHost() 方法创建的InetAddress的对象
InetAddress address = InetAddress.getLocalHost();
System.out.println(address.getHostName());//主机名
System.out.println(address.getCanonicalHostName());//主机别名
System.out.println(address.getHostAddress());//获取IP地址
System.out.println("===============");
//用域名创建 InetAddress对象
InetAddress address1 = InetAddress.getByName("www.wodexiangce.cn");
//获取的是该网站的ip地址,如果我们所有的请求都通过nginx的,所以这里获取到的其实是nginx服务器的IP地址
System.out.println(address1.getHostName());//www.wodexiangce.cn
System.out.println(address1.getCanonicalHostName());//124.237.121.122
System.out.println(address1.getHostAddress());//124.237.121.122
System.out.println("===============");
//用IP地址创建InetAddress对象
InetAddress address2 = InetAddress.getByName("220.181.111.188");
System.out.println(address2.getHostName());//220.181.111.188
System.out.println(address2.getCanonicalHostName());//220.181.111.188
System.out.println(address2.getHostAddress());//220.181.111.188
System.out.println("===============");
//根据主机名返回其可能的所有InetAddress对象
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
for (InetAddress addr : addresses) {
System.out.println(addr);
//www.baidu.com/220.181.111.188
//www.baidu.com/220.181.112.244
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
可以知道此时获取到的服务器如果加了代理方式就是获取到代理的地址,一般会使用netty代理转发。文章来源:https://www.toymoban.com/news/detail-505760.html
/**
* 获取服务器IP地址
* @return
*/
@SuppressWarnings("unchecked")
public static String getServerIp(){
String SERVER_IP = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
ip = (InetAddress) ni.getInetAddresses().nextElement();
SERVER_IP = ip.getHostAddress();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
SERVER_IP = ip.getHostAddress();
break;
} else {
ip = null;
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SERVER_IP;
}
我的解决死方法(方法是死的,但是能解决问题^_^)
在nacos的配置里面新建一个文章来源地址https://www.toymoban.com/news/detail-505760.html
constant.ipHost=服务器的ip
//获取服务器的ip @Value("${constant.ipHost}") private String ipHost;
到了这里,关于Java中获取当前服务器的IP地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!