1import java.net.Inet4Address; 2import java.net.InetAddress; 3import java.net.NetworkInterface; 4import java.util.Enumeration; 5 6import javax.servlet.http.HttpServletRequest; 7 8/** 9 * @version v1.0 10 * @Description: TODO 11 * @Author: cnb 12 * @Date: 2020/1/18 23:08 13 */ 14public class IpUtils { 15 16 private static final String[] HEADERS = { 17 "X-Forwarded-For", 18 "Proxy-Client-IP", 19 "WL-Proxy-Client-IP", 20 "HTTP_X_FORWARDED_FOR", 21 "HTTP_X_FORWARDED", 22 "HTTP_X_CLUSTER_CLIENT_IP", 23 "HTTP_CLIENT_IP", 24 "HTTP_FORWARDED_FOR", 25 "HTTP_FORWARDED", 26 "HTTP_VIA", 27 "REMOTE_ADDR", 28 "X-Real-IP" 29 }; 30 31 /** 32 * 判断ip是否为空,空返回true 33 * @param ip 34 * @return 35 */ 36 public static boolean isEmptyIp(final String ip){ 37 return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip)); 38 } 39 40 41 /** 42 * 判断ip是否不为空,不为空返回true 43 * @param ip 44 * @return 45 */ 46 public static boolean isNotEmptyIp(final String ip){ 47 return !isEmptyIp(ip); 48 } 49 50 /*** 51 * 获取客户端ip地址(可以穿透代理) 52 * @param request HttpServletRequest 53 * @return 54 */ 55 public static String getIpAddress(HttpServletRequest request) { 56 String ip = ""; 57 for (String header : HEADERS) { 58 ip = request.getHeader(header); 59 if(isNotEmptyIp(ip)) { 60 break; 61 } 62 } 63 if(isEmptyIp(ip)){ 64 ip = request.getRemoteAddr(); 65 } 66 if(isNotEmptyIp(ip) && ip.contains(",")){ 67 ip = ip.split(",")[0]; 68 } 69 if("0:0:0:0:0:0:0:1".equals(ip)){ 70 ip = "127.0.0.1"; 71 } 72 return ip; 73 } 74 75 76 /** 77 * 获取本机的局域网ip地址,兼容Linux 78 * @return String 79 * @throws Exception 80 */ 81 public String getLocalHostIP() throws Exception{ 82 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); 83 String localHostAddress = ""; 84 while(allNetInterfaces.hasMoreElements()){ 85 NetworkInterface networkInterface = allNetInterfaces.nextElement(); 86 Enumeration<InetAddress> address = networkInterface.getInetAddresses(); 87 while(address.hasMoreElements()){ 88 InetAddress inetAddress = address.nextElement(); 89 if(inetAddress != null && inetAddress instanceof Inet4Address){ 90 localHostAddress = inetAddress.getHostAddress(); 91 } 92 } 93 } 94 return localHostAddress; 95 } 96 97}
Java获取IP地址
Wesley13
2021-10-11
1297 0 0
点赞
收藏
评论区
加载中...