zoukankan      html  css  js  c++  java
  • Java IP地址工具类

    Java IP地址工具类

    • POM依赖
    <!-- https://mvnrepository.com/artifact/org.lionsoul/ip2region -->
    <dependency>
        <groupId>org.lionsoul</groupId>
        <artifactId>ip2region</artifactId>
        <version>1.7.2</version>
    </dependency>
    
    • java代码
    package cn.pconline.common.utils;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    import org.apache.commons.io.FileUtils;
    import org.lionsoul.ip2region.DataBlock;
    import org.lionsoul.ip2region.DbConfig;
    import org.lionsoul.ip2region.DbSearcher;
    import org.lionsoul.ip2region.Util;
    
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.Objects;
    
    /**
     * @Description IP地址工具类
     * @Author jie.zhao
     * @Date 2019/8/15 11:53
     */
    @Slf4j
    @Component
    public class IPUtil {
    
        private static final String UNKNOWN = "unknown";
        private static final String LOCAL_IPV4 = "127.0.0.1";
        private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";
    
        /**
         * 获取客户端IP地址
         *
         * @param request 请求
         * @return
         */
        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.getRemoteAddr();
                if (LOCAL_IPV4.equals(ip)) {
                    //根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ip = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ip != null && ip.length() > 15) {
                if (ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
            if (LOCAL_IPV6.equals(ip)) {
                ip = "127.0.0.1";
            }
            return ip;
        }
    	
    	/**
    	 * 获取IP地址所在城市
    	 *
    	 * https://github.com/lionsoul2014/ip2region
    	 */
    	public static String getCityInfo(String ip) {
            DbSearcher searcher = null;
            try {
                String dbPath = IPUtil.class.getResource("/ip2region/ip2region.db").getPath();
                File file = new File(dbPath);
                if (!file.exists()) {
                    String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
                    dbPath = tmpDir + "ip.db";
                    file = new File(dbPath);
                    FileUtils.copyInputStreamToFile(Objects.requireNonNull(IPUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db")), file);
                }
                int algorithm = DbSearcher.BTREE_ALGORITHM;
                DbConfig config = new DbConfig();
                searcher = new DbSearcher(config, file.getPath());
                Method method = searcher.getClass().getMethod("btreeSearch", String.class);
                DataBlock dataBlock = null;
                if (!Util.isIpAddress(ip)) {
                    log.error("Error: Invalid ip address");
                }
                dataBlock = (DataBlock) method.invoke(searcher, ip);
                return dataBlock.getRegion();
            } catch (Exception e) {
                log.error("获取地址信息异常", e);
            } finally {
                if (searcher != null) {
                    try {
                        searcher.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "";
        }
    }
    
  • 相关阅读:
    Django通用视图执行过程
    Django HTTP处理流程(自我总结)
    CentOS 安装MySQL5.7
    Python--定时给Ta讲笑话
    【转】对Django框架架构和Request/Response处理流程的分析
    Python模块发布
    Django中使用CKEditor代码高亮显示插件Code Snippet
    页面中的"返回顶部"(位置固定,指定位置显示/隐藏) Label:博客园美化
    跨域请求配置 Amazon AWS S3 腾讯云 阿里云 COS OSS 文件桶解决方案以及推荐 Label:Research
    文件分发服务器 AWS CloudFront(CDN)使用入门-以S3为例 Label:Research
  • 原文地址:https://www.cnblogs.com/cnsyear/p/12714257.html
Copyright © 2011-2022 走看看