tianze-pro/web/src/main/java/cn/jlw/util/IpUtils.java

267 lines
8.2 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package cn.jlw.util;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.jlw.entity.IpAddress;
import com.ibeetl.jlw.service.IpAddressService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static cn.hutool.core.net.NetUtil.ipv4ToLong;
import static cn.jlw.util.ToolUtils.subString;
import static com.ibeetl.jlw.web.IpAddressController.ipAddressMap;
public class IpUtils {
private static TaskCallable taskCallable = new TaskCallable();
// 分隔符1
public static final String SEPARATOR = "\\,";
// 分隔符2
public static final String IP_SPLIT_MARK = "\\-";
// 分隔符3
public static final String IP_SPLIT_SEPARATOR = "\\.";
private IpUtils() {
}
/**
* 获取当前网络ip
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
if(null != ipAddressMap && null == ipAddressMap.get(ipAddress)){
IpAddress ipAddressPojo = new IpAddress();
ipAddressPojo.setIp(ipAddress);
taskCallable.start(ipAddressPojo);
}
return ipAddress;
}
/**
* 获得MAC地址
*
* @param ip
* @return
*/
public static String getMACAddress(String ip) {
String str = "";
String 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) {
e.printStackTrace(System.out);
}
return macAddress;
}
/**
* 验证IP区间是否符合要求
*
*
* @param ipAddressList 支持格式x.x.x.x-x.x.x.x,x.x.x.x-x.x.x.x。多个IP段逗号隔开
*/
public static void verifyIpRange(String ipAddressList) {
Assert.notBlank(ipAddressList, "待验证的IP区间不能为空");
for (String ipRange : ipAddressList.split(SEPARATOR)) {
String reg = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}" +
"-((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$";
Assert.isTrue(ReUtil.isMatch(reg, ipRange),
() -> new PlatformException("ipAddressList 参数格式化错误支持格式x.x.x.x-x.x.x.x,x.x.x.x-x.x.x.x"));
}
}
/**
* ID是否在IP区间内
*
* @param myIpAddress
* @param ipAddressList 支持格式x.x.x.x-x.x.x.x,x.x.x.x-x.x.x.x。多个IP段逗号隔开
* @return
*/
public static Boolean isRangeInner(String myIpAddress, String ipAddressList) throws PlatformException {
verifyIpRange(ipAddressList);
// 我的IPv4转long类型
long myIpLong = ipv4ToLong(myIpAddress);
// 是否在IP段区间
Boolean isRangeInner = false;
// 处理IP段判断IP是否在这个区间内 192.168.1.1-192.168.1.100,192.168.2.1-192.168.2.100
for (String range : ipAddressList.split(SEPARATOR)) {
// 两个IP段。开始IP-结束IP
String[] ips = range.split(IP_SPLIT_MARK);
long startIpLong = ipv4ToLong(ips[0]);
long endIpLong = ipv4ToLong(ips[1]);
// 在区间内,则打标记
if((myIpLong >= startIpLong) && (myIpLong <= endIpLong)) {
isRangeInner = true;
}
}
return isRangeInner;
}
public static class TaskCallable implements Callable<Boolean> {
private Log log = LogFactory.getLog(IpUtils.class);
private ExecutorService pool = Executors.newFixedThreadPool(2);
IpAddress ipAddress;
public TaskCallable() {
}
public TaskCallable(IpAddress ipAddress) {
this.ipAddress = ipAddress;
}
@Override
public Boolean call() {
try {
log.info("似乎有新的IP");
if(null != ipAddress && StringUtils.isNotBlank(ipAddress.getIp())){
if(null == ipAddressMap.get(ipAddress.getIp())){
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("ip", ipAddress.getIp()));
params.add(new BasicNameValuePair("json", "true"));
try {
String address = httpPost("http://whois.pconline.com.cn/ipJson.jsp",params).replace("\n","").replace("\r","");
if(StringUtils.isNotBlank(address) && address.contains("pro") && address.contains("city") && address.contains("region")){
ipAddress.setProvince(subString(address,"\"pro\":\"","\","));
ipAddress.setCity(subString(address,"\"city\":\"","\","));
ipAddress.setDistrict(subString(address,"\"region\":\"","\","));
IpAddressService ipAddressService = (IpAddressService) SpringContextUtil.getBean("ipAddressService");
ipAddressService.insert(ipAddress);
ipAddressMap.put(ipAddress.getIp(),ipAddress);//丢到缓存里
log.info("有新的IP");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public void start(IpAddress ipAddress){
List<Future<Boolean>> results = new ArrayList<>();
results.add(pool.submit(new TaskCallable(ipAddress)));
}
public static String httpPost(String url,List<NameValuePair> params) {
String result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if(params != null)
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
}
} catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is,"GBK"));
} catch (UnsupportedEncodingException e) {
reader = new BufferedReader(new InputStreamReader(is));
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String sss = sb.toString();
return sss;
}
}
}