获取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代理转发。
/** * 获取服务器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的配置里面新建一个
constant.ipHost=服务器的ip
//获取服务器的ip @Value("${constant.ipHost}") private String ipHost;
总结
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)