根据IP地址自动识别省份城市

这段博客介绍了如何通过代码实现根据IP地址自动识别出对应的省份和城市,提供了相关的编程实例。
摘要由CSDN通过智能技术生成



功能说明:需要获取客户端的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 =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值