一、Java获取服务器IP(转自:https://www.cnblogs.com/george93/p/6306579.html)
//方法一,也是最简单的一种。 String SERVER_IP = InetAddress.getLocalHost().getHostAdress().toString(); //方法二: /** * 获取服务器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; } }
二、Java获取客户端IP(转自:http://www.cnblogs.com/ITtangtang/p/3927768.html)
其核心思想是通过HTTP的Servlet来获取;
//第一种 /** * 从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip * @param request * @return ip */ public static String getLocalIp(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String forwarded = request.getHeader("X-Forwarded-For"); String realIp = request.getHeader("X-Real-IP"); String ip = null; if (realIp == null) { if (forwarded == null) { ip = remoteAddr; } else { ip = remoteAddr + "/" + forwarded.split(",")[0]; } } else { if (realIp.equals(forwarded)) { ip = realIp; } else { if(forwarded != null){ forwarded = forwarded.split(",")[0]; } ip = realIp + "/" + forwarded; } } return ip; } //第二种 public static String getIp(HttpServletRequest request) { String remoteAddr = request.getRemoteAddr(); String forwarded = request.getHeader("X-Forwarded-For"); String realIp = request.getHeader("X-Real-IP"); String ip = null; if (realIp == null) { if (forwarded == null) { ip = remoteAddr; } else { ip = remoteAddr + "/" + forwarded; } } else { if (realIp.equals(forwarded)) { ip = realIp; } else { ip = realIp + "/" + forwarded.replaceAll(", " + realIp, ""); } } return ip; } //第三种,也是最清晰合理的一种 public static String getIp2(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){ //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if(index != -1){ return ip.substring(0,index); }else{ return ip; } } ip = request.getHeader("X-Real-IP"); if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){ return ip; } return request.getRemoteAddr(); }
原文地址:https://www.cnblogs.com/su-zhifei/p/9593676.html
时间: 2024-10-21 08:39:45