某些业务场景需要对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;
}