com.github.ipaas.ifw.util.IPUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.github.ipaas.ifw.util.IPUtil.java

Source

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.ipaas.ifw.util;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ??IP?
 * 
 * * @author Chenql
 * 
 */
public class IPUtil {

    private static final Logger logger = LoggerFactory.getLogger(IPUtil.class);

    private static List<InetAddress> localAddressList;

    static {
        // ??
        localAddressList = getLocalAddresses();
    }

    /**
     * IP???
     * 
     * @param ip
     * @return
     */
    public static long convertIpToInt(String ip) {
        // IP
        String[] ipArray = StringUtils.split(ip, '.');
        // IP
        long ipInt = 0;
        // 
        try {
            for (int i = 0; i < ipArray.length; i++) {
                if (ipArray[i] == null || ipArray[i].trim().equals("")) {
                    ipArray[i] = "0";
                }
                if (new Integer(ipArray[i].toString()).intValue() < 0) {
                    Double j = new Double(Math.abs(new Integer(ipArray[i].toString()).intValue()));
                    ipArray[i] = j.toString();
                }
                if (new Integer(ipArray[i].toString()).intValue() > 255) {
                    ipArray[i] = "255";
                }
            }
            ipInt = new Double(ipArray[0]).longValue() * 256 * 256 * 256
                    + new Double(ipArray[1]).longValue() * 256 * 256 + new Double(ipArray[2]).longValue() * 256
                    + new Double(ipArray[3]).longValue();
            // 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ipInt;
    }

    /**
     * ?IP???IP?IP??
     * 
     * @return IP
     */
    public static String getLocalIP() {
        return getLocalIP(false);
    }

    /**
     * ?IP? ??IP
     * 
     * @param isInter
     *            ?IP19.2.
     * @return ip?
     */
    public static String getLocalIP(boolean isInter) {
        String localIP = "";
        for (InetAddress ia : localAddressList) {
            String ip = ia.getHostAddress();
            // ipv6?loopback?
            if (ia instanceof Inet6Address || ip.startsWith("127")) {
                continue;
            }
            // ipv4?
            if (StringUtil.isNullOrBlank(localIP)) {
                localIP = ip;
            }
            if (isInter && ip.startsWith("19.")) {
                return ip;
            }
            if (!isInter && !ip.startsWith("19.")) {
                return ip;
            }
        }
        return localIP;
    }

    /**
     * ??IP?
     * 
     * @param address
     *            ?
     * @return IP?true?false
     */
    public static boolean isIP(String address) {
        // ?ip?
        Pattern ipPattern = Pattern.compile("\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b");
        return ipPattern.matcher(address).matches();
    }

    /**
     * ??
     * 
     * @return
     */
    public static List<InetAddress> getLocalAddresses() {
        if (localAddressList == null) {
            localAddressList = new ArrayList<InetAddress>();
            try {
                // ???
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces != null && interfaces.hasMoreElements()) {
                    NetworkInterface interfaceN = interfaces.nextElement();
                    // ???
                    Enumeration<InetAddress> ienum = interfaceN.getInetAddresses();
                    while (ienum.hasMoreElements()) {
                        InetAddress ia = ienum.nextElement();
                        // ??
                        localAddressList.add(ia);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("???[{}]", localAddressList);
        }
        return localAddressList;
    }

    /**
     * ?IP?
     * 
     * @param request
     *            http
     * @return IP?
     */
    public static String getUserIP(HttpServletRequest request) {
        return getClientIP(request, 0);
    }

    /**
     * ?WapIP
     * 
     * @param request
     * @return
     */
    public static String getWapUserIP(HttpServletRequest request) {
        return getClientIP(request, 1);
    }

    /**
     * ?IP
     */
    public static String getNearestClientIP(HttpServletRequest request) {
        return getClientIP(request, 2);
    }

    /**
     * ???IP
     * 
     * @param request
     *            http
     * @param mode
     *            0:user ip, 1:wap user ip, 2: nearest client ip
     * @return
     */
    private static String getClientIP(HttpServletRequest request, int mode) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        } else {
            String[] ips = ip.split(",");
            ip = ips[0].trim();
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        } else {
            return ip.trim();
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip.trim();
    }

    /**
     * 
     * ??
     * 
     * @param request
     *            http
     * @return int
     */
    public static int getUserPort(HttpServletRequest request) {
        String portStr = request.getHeader("Ty_Remote_Port");
        if (StringUtil.isNullOrBlank(portStr))
            return request.getRemotePort();
        try {
            return Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            return request.getRemotePort();
        }
    }

}