Java獲取使用者IP地址的工具類
阿新 • • 發佈:2018-11-19
package com.gcloud.common; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Description: IP工具類 * @Author: zhangzhixiang * @CreateDate: 2018/11/08 16:08:54 * @Version: 1.0 */ public class IPUtil { /** * 檢查IP是否合法 * @param ip * @return */ public static boolean ipValid(String ip) { String regex0 = "(2[0-4]\\d)" + "|(25[0-5])"; String regex1 = "1\\d{2}"; String regex2 = "[1-9]\\d"; String regex3 = "\\d"; String regex = "(" + regex0 + ")|(" + regex1 + ")|(" + regex2 + ")|(" + regex3 + ")"; regex = "(" + regex + ").(" + regex + ").(" + regex + ").(" + regex + ")"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ip); return m.matches(); } /** * 獲取本地ip 適合windows與linux * * @return */ public static String getLocalIP() { String localIP = "127.0.0.1"; try { Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); InetAddress ip = ni.getInetAddresses().nextElement(); if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { localIP = ip.getHostAddress(); break; } } } catch (Exception e) { try { localIP = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e1) { e1.printStackTrace(); } } return localIP; } /** * 獲取客戶機的ip地址 * @param request * @return */ public static String getClientIp(HttpServletRequest request) { String 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(); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("http_client_ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } // 如果是多級代理,那麼取第一個ip為客戶ip if (ip != null && ip.indexOf(",") != -1) { ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); } return ip; } /** * 把ip轉化為整數 * @param ip * @return */ public static long translateIP2Int(String ip){ String[] intArr = ip.split("\\."); int[] ipInt = new int[intArr.length]; for (int i = 0; i <intArr.length ; i++) { ipInt[i] = new Integer(intArr[i]).intValue(); } return ipInt[0] * 256 * 256 * 256 + + ipInt[1] * 256 * 256 + ipInt[2] * 256 + ipInt[3]; } }