You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.1 KiB
62 lines
2.1 KiB
package com.fr.plugin; |
|
|
|
import javax.servlet.http.HttpServletRequest; |
|
|
|
public class IpUtils { |
|
/** |
|
* 将字符串形式IP地址127.0.0.1转换10234564321 |
|
* |
|
* @param strIP |
|
* @return |
|
*/ |
|
public static long ip2Long(String strIP) { |
|
long[] ip = new long[4]; |
|
// 先找到IP地址字符串中.的位置 |
|
int position1 = strIP.indexOf("."); |
|
int position2 = strIP.indexOf(".", position1 + 1); |
|
int position3 = strIP.indexOf(".", position2 + 1); |
|
// 将每个.之间的字符串转换成整型 |
|
ip[0] = Long.parseLong(strIP.substring(0, position1)); |
|
ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2)); |
|
ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3)); |
|
ip[3] = Long.parseLong(strIP.substring(position3 + 1)); |
|
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; |
|
} |
|
|
|
public static String getIp(HttpServletRequest request) { |
|
String remoteIp = request.getRemoteAddr(); |
|
|
|
// 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 |
|
if (remoteIp != null && remoteIp.length() > 15) { |
|
if (remoteIp.indexOf(",") > 0) { |
|
remoteIp = remoteIp.substring(0, remoteIp.indexOf(",")); |
|
} |
|
} |
|
return remoteIp; |
|
} |
|
|
|
/** |
|
* 将字符串形式IP地址转换long类型 |
|
* @param ip |
|
* @return |
|
*/ |
|
public static long getIp2long(String ip) { |
|
ip = ip.trim(); |
|
String[] ips = ip.split("\\."); |
|
long ip1 = Integer.parseInt(ips[0]); |
|
long ip2 = Integer.parseInt(ips[1]); |
|
long ip3 = Integer.parseInt(ips[2]); |
|
long ip4 = Integer.parseInt(ips[3]); |
|
return ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4; |
|
} |
|
/** |
|
* 判断一个ip地址是否在某个ip段范围内 |
|
* @param ip |
|
* @param startIP |
|
* @param endIP |
|
* @return |
|
*/ |
|
public static boolean ipExistsInRange(String ip, String startIP, String endIP) { |
|
return (getIp2long(startIP)<=getIp2long(ip)) && (getIp2long(ip)<=getIp2long(endIP)); |
|
} |
|
}
|
|
|