Java ip来源或终端判断工具类

直接上代码

import org.apache.commons.lang.text.StrTokenizer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: IpUtil 
 * @Description: user-agent
 * user-agent 值可参考以下值
 * https://blog.csdn.net/u012175089/article/details/61199238/
 * @author JornTang
 * @email 957707261@qq.com
 * @date 2017年8月17日
 */
public class IpUtil {
    private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
    
    public static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";  
    public static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");

    private static final String ANYHOST = "0.0.0.0";
    private static final String LOCALHOST = "127.0.0.1";
    public static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

    private static volatile InetAddress LOCAL_ADDRESS = null;
    
    /** 
     * 访问来源
     */  
    public static String ipFrom(HttpServletRequest request){ 
        
        String requestHeader = request.getHeader("user-agent");
        if(StringUtils.isEmpty(requestHeader)) {
            return "未知来源";
        }
        
        requestHeader = requestHeader.toLowerCase();
        // 苹果
        String[] macDeviceArr = new String[] {"mac os", "ipad", "ipod", "iphone"};
        for(int i = 0; i< macDeviceArr.length; i++) {
            if(requestHeader.indexOf(macDeviceArr[i]) > 0) {
                return "苹果";
            }
        }
        
        // 安卓
        String[] androidDeviceArr = new String[] {"android", "adr"};
        for(int i = 0; i< androidDeviceArr.length; i++) {
            if(requestHeader.indexOf(androidDeviceArr[i]) > 0) {
                return "安卓";
            }
        }
        
        // 其他移动端
        String[] othDeviceArr = new String[] {"mobile", "windows phone", "windows ce"};
        for(int i = 0; i< othDeviceArr.length; i++) {
            if(requestHeader.indexOf(othDeviceArr[i]) > 0) {
                return "其他移动端";
            }
        }
        
        return "PC端";
    }
    /** 
     * 终端名称
     */  
    public static String terminal(HttpServletRequest request){ 
        
        String requestHeader = request.getHeader("user-agent");
        if(StringUtils.isEmpty(requestHeader)) {
            return "未知终端";
        }
        
        requestHeader = requestHeader.toLowerCase();
        // ipad
        String[] ipadDeviceArr = new String[] {"ipad", "ipod"};
        for(int i = 0; i< ipadDeviceArr.length; i++) {
            if(requestHeader.indexOf(ipadDeviceArr[i]) > 0) {
                return "ipad";
            }
        }
        
        
        // 手机
        String[] mobileDeviceArr = new String[] {"android", "adr", "iphone", "mobile", "windows phone", "windows ce"};
        for(int i = 0; i< mobileDeviceArr.length; i++) {
            if(requestHeader.indexOf(mobileDeviceArr[i]) > 0) {
                return "手机";
            }
        }
        
        // 电脑
        String[] pcDeviceArr = new String[] {"windowsnt", "windows nt"};
        for(int i = 0; i< pcDeviceArr.length; i++) {
            if(requestHeader.indexOf(pcDeviceArr[i]) > 0) {
                return "电脑";
            }
        }
        return "其他";
    }
    /** 
     * 浏览器类型
     */  
    public static String browser(HttpServletRequest request){ 
        
        String requestHeader = request.getHeader("user-agent");
        if(StringUtils.isEmpty(requestHeader)) {
            return "未知来源";
        }
        
        requestHeader = requestHeader.toLowerCase();
        String[] browserArr = new String[] {"msie", "firefox", "chrome", "opera", "safari", "360se", "ucweb", "qqbrowser", "tencenttraveler"};
        for(int i = 0; i< browserArr.length; i++) {
            if(requestHeader.indexOf(browserArr[i]) > 0) {
                return browserArr[i];
            }
        }
        
        return "其他浏览器";
    }
    /**
     * valid address
     * @param address
     * @return
     */
    private static boolean isValidAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress())
            return false;
        String name = address.getHostAddress();
        return (name != null
                && ! ANYHOST.equals(name)
                && ! LOCALHOST.equals(name)
                && IP_PATTERN.matcher(name).matches());
    }

    /**
     * get first valid addredd
     * @return
     */
    private static InetAddress getFirstValidAddress() {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
            logger.error("Failed to retriving ip address, " + e.getMessage(), e);
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable e) {
                                    logger.error("Failed to retriving ip address, " + e.getMessage(), e);
                                }
                            }
                        }
                    } catch (Throwable e) {
                        logger.error("Failed to retriving ip address, " + e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("Failed to retriving ip address, " + e.getMessage(), e);
        }
        logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");
        return localAddress;
    }

    /**
     * get address
     * @return
     */
    private static InetAddress getAddress() {
        if (LOCAL_ADDRESS != null)
            return LOCAL_ADDRESS;
        InetAddress localAddress = getFirstValidAddress();
        LOCAL_ADDRESS = localAddress;
        return localAddress;
    }
    /** 
     * 获取当前网络ip 
     * @param request 
     * @return 
     */  
    public static String getIpAddr(HttpServletRequest request){  
        String ipAddress = request.getHeader("x-forwarded-for");  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getHeader("WL-Proxy-Client-IP");  
            }  
            if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  
                ipAddress = request.getRemoteAddr();  
                if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  
                    //根据网卡取本机配置的IP  
                    InetAddress inet=null;  
                    try {  
                        inet = InetAddress.getLocalHost();  
                    } catch (UnknownHostException e) {  
                        e.printStackTrace();  
                    }  
                    ipAddress= inet.getHostAddress();  
                }  
            }  
            //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  
            if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  
                if(ipAddress.indexOf(",")>0){  
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  
                }  
            }  
            return ipAddress;   
    }

    /**
     * get ip
     * @return
     */
    public static String getIp(){
        InetAddress address = getAddress();
        if (address==null) {
            return null;
        }
        return address.getHostAddress();
    }

    /**
     * get ip:port
     * @param port
     * @return
     */
    public static String getIpPort(int port){
        String ip = getIp();
        if (ip==null) {
            return null;
        }
        return ip.concat(":").concat(String.valueOf(port));
    }

    public static void main(String[] args) throws UnknownHostException {
        System.out.println(getFirstValidAddress());
        System.out.println(getIpPort(8080));
    }
    public static String longToIpV4(long longIp) {  
        int octet3 = (int) ((longIp >> 24) % 256);  
        int octet2 = (int) ((longIp >> 16) % 256);  
        int octet1 = (int) ((longIp >> 8) % 256);  
        int octet0 = (int) ((longIp) % 256);  
        return octet3 + "." + octet2 + "." + octet1 + "." + octet0;  
    }  
  
    public static long ipV4ToLong(String ip) {  
        String[] octets = ip.split("\\.");  
        return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16)  
                + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);  
    }  
  
    public static boolean isIPv4Private(String ip) {  
        long longIp = ipV4ToLong(ip);  
        return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255"))  
                || (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255"))  
                || longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255");  
    }  
  
    public static boolean isIPv4Valid(String ip) {  
        return pattern.matcher(ip).matches();  
    }  
  
    public static String getIpFromRequest(HttpServletRequest request) {  
        String ip;  
        boolean found = false;  
        if ((ip = request.getHeader("x-forwarded-for")) != null) {  
            StrTokenizer tokenizer = new StrTokenizer(ip, ",");  
            while (tokenizer.hasNext()) {  
                ip = tokenizer.nextToken().trim();  
                if (isIPv4Valid(ip) && !isIPv4Private(ip)) {  
                    found = true;  
                    break;  
                }  
            }  
        }  
        if (!found) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }  
    /**
     * 获取用户IP地址
     * 
     * @param request
     * @return
     */
    public static String getIpAddrs(final 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 (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");
        }
        // 如果是多级代理,那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        if (ip.indexOf("0:") != -1) {
            ip = "本地";
        }
        StringBuffer sb=new StringBuffer();
        sb.append(";x-forwarded-for:"+request.getHeader("x-forwarded-for"));
        sb.append(";Proxy-Client-IP:"+request.getHeader("Proxy-Client-IP"));
        sb.append(";WL-Proxy-Client-IP:"+request.getHeader("WL-Proxy-Client-IP"));
        sb.append("getRemoteAddr:"+request.getRemoteAddr());
        sb.append(";http_client_ip:"+request.getHeader("http_client_ip"));
        sb.append(";HTTP_X_FORWARDED_FOR:"+request.getHeader("HTTP_X_FORWARDED_FOR"));
//      log.error("获取ip:"+sb.toString()+"\n头部信息");
        Enumeration he=request.getHeaderNames();
        while(he.hasMoreElements()){
            Object name=he.nextElement();
            String value=request.getHeader(name.toString());
            sb.append("header:"+name);
            sb.append("="+value+",headers:");
            Enumeration e=request.getHeaders(name.toString());
            while(e.hasMoreElements()){
               sb.append((String ) e.nextElement()+"------");
            }
            sb.append("\n");
        }
        return ip;
    }
}

作者:[云软科技-档案管理系统](http://www.gzyrkj.net) JornTang (微信同号)

本篇文章由一文多发平台ArtiPub自动发布

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • 最近入手了HomePod,顺手也就开通了Apple Music,于是也就有了这篇 网易云歌单转Apple Musi...
    TreviD阅读 11,695评论 1 4
  • 对于穷人来说,读书可以弥补物质困乏而带来的满足感。没有物质,无法去周游世界,无法购买自己喜欢的衣服与车子还有房屋,...
    冷雨悠悠阅读 302评论 0 0
  • 舒婷曾经说过一句话:“人到中年,朋友的多少和头发的多少成正比,友情之树日渐凋零。”这是中年人的朋友圈现象,而今我这...
    青梦0103阅读 555评论 0 0
  • 今天早上去辅导部学舞蹈的时候,我来迟了。老师今天教了我们一个新的舞蹈,名字是天天向上。音乐很快。我们都跟不上,妈妈...
    芙蓉花开_ba44阅读 157评论 0 0