import javax.servlet.http.HttpServletRequest;
/**
* IP处理工具类
*
* @author lixunhui@qq.com
*
*/
public class IPUtil {
/**
* 获取真实IP:
* 先取
* @param request
* @return
*/
public static String getClientIP(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* IP转成数字类型
*
* @param strIP
* @return
*/
public static long ipToLong(String strIP) {
long[] ip = new long[4];
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));
// ip1*256*256*256+ip2*256*256+ip3*256+ip4
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
/**
* 是否是本地IP
*
* @param strIp
* @return
*/
public static boolean isLocal(String strIp) {
if ("127.0.0.1".equals(strIp))
return true;
long l = ipToLong(strIp);
if (l >= 3232235520L)
return l <= 3232301055L;
return (l >= 167772160L) && (l <= 184549375L);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("202.102.249.59:"
+ Long.toString(IPUtil.ipToLong("202.102.249.59")));
System.out.println("202.102.249.59 is local ip:"
+ Boolean.toString(IPUtil.isLocal("202.102.249.59")));
System.out.println("127.0.0.1:"
+ Long.toString(IPUtil.ipToLong("127.0.0.1")));
System.out.println("127.0.0.1 is local ip:"
+ Boolean.toString(IPUtil.isLocal("127.0.0.1")));
System.out.println("10.9.1.134:"
+ Long.toString(IPUtil.ipToLong("10.9.1.134")));
System.out.println("10.9.1.134 is local ip:"
+ Boolean.toString(IPUtil.isLocal("10.9.1.134")));
}
}