天天看點

常用工具類 — Ip工具類

某些業務場景需要對IP進行操作,包括擷取登入使用者的IP位址、對IP進行加密處理、判斷該字串是否為IP以及擷取用戶端Mac位址的操作,接下來将針對這些操作實作一個常用工具類,友善後續複用。

01—擷取登入使用者的IP位址

/**
 * 擷取登入使用者的IP位址
 * @param request 請求
 * @return
 */
public static String getIpAddr(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.equals("0:0:0:0:0:0:0:1")) {
      ip = "本地";
   }
   if (ip.split(",").length > 1) {
      ip = ip.split(",")[0];
   }
   return ip;
}      

02—判斷是否為IP

/**
 * 判斷該字串是否為IP
 * @param ipStr  IP字串
 * @return
 */
public static boolean isIP(String ipStr) {
  String ip = "(25[0-5]|2[0-4]\\d|1\\d\\d|\\d\\d|\\d)";
  String ipDot = ip + "\\.";
  return ipStr.matches(ipDot + ipDot + ipDot + ip);
}      

03—IP加密處理

/**
 * IP加密處理
 * @param ip  需要進行處理的IP
 * @return
 */
public static String hideIp(String ip) {
  if (StringUtil.isEmpty(ip)) {
    return "";
  }
  int pos = ip.lastIndexOf(".");
  if (pos == -1) {
    return ip;
  }
  ip = ip.substring(0, pos + 1);
  ip = ip + "*";
  return ip;
}      

04—擷取用戶端Mac位址

/**
 * 擷取用戶端Mac位址
 * @param ip
 * @return
 */
public static String getMACAddress(String ip) {
  String str = "";
  String macAddress = "";    
  if(StringUtil.isEmpty(ip)){
    return macAddress;
  }
  try {
    Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
    InputStreamReader ir = new InputStreamReader(p.getInputStream());
    LineNumberReader input = new LineNumberReader(ir);
    for (int i = 1; i < 100; i++) {
      str = input.readLine();
      if (str != null) {
        if (str.indexOf("MAC Address") > 1) {
          macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
          break;
        }
      }
    }
  } catch (IOException e) {
    return "";
  }
  return macAddress;
}