JAVA 优先获取外网Ip,再获取内网Ip
1、获取内网Ip
private String getLocalhostIp(){ String hostAddress = ""; try { InetAddress address = InetAddress.getLocalHost(); hostAddress = address.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } return hostAddress; }
2、获取外网Ip
private String getRemoteAddr() { String ip =""; try { ip =request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip =request.getRemoteAddr(); } return ip.split(",")[0]; } catch (Exception e) { e.printStackTrace(); } return ip; }
3、获取用户Ip
public String getIpAddr(){ String ip = this.getRemoteAddr(); if("".equals(ip)){ ip = this.getLocalhostIp(); } return ip; }
版权声明:如需转载,请注明!PS:如是转载随便,请忽略