功能说明:需要获取客户端的IP地址,自动识别省份
代码如下:
获取IP地址:
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.getHeader("HTTP_CLIENT_IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
ip = request.getRemoteAddr();
if ("0:0:0:0:0:0:0:1".equals(ip.trim())) {
ip = "127.0.0.1";
}
return ip;
}
调用
String clientIp = PortalToolsUtil.getIpAddr(portalRequest);
根据IP地址获取省份类:
public class IpAddress {
private Logger LogUtil = Logger.getLogger(IpAddress.class);
// 随机文件访问类
private RandomAccessFile ipFile = null;
// 单一模式实例
private static IpAddress instance = new IpAddress();
// ip开始结束位置
private long ipBegin = 0L;
private long ipEnd = 0L;
// ip总数
private long ipSum = 0L;
// 国家,地区
private String country = "";
private String area = "";
// 一些固定常量,比如记录长度等等
private static final int RECORD_LENGTH = 7;
private static final byte AREA_FOLLOWED = 0x01;
private static final byte NO_AREA = 0x02;
/*
* 私有构造函数
*/
private IpAddress() {
// 数据库地址
String dataPath = PropUtil.getProp("ipfile");
try {
ipFile = new RandomAccessFile(new File(dataPath).getAbsolutePath(),"r");
} catch (FileNotFoundException e) {
LogUtil.error("IP地址信息文件没有找到(QQWry.Dat),IP显示功能将无法使用");
}
if (ipFile != null) {
try {
ipBegin = byteArrayToLong(readBytes(0, 4));
ipEnd = byteArrayToLong(readBytes(4, 4));
if (ipBegin =