针对各种对ip需求的工具类

注释

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

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtil {
public static final String ZEROIP = “0.0.0.0”;
private static final Logger LOGGER = LoggerFactory.getLogger(IPUtil.class.getName());
private static String mac;
private static String localServerIP = “”;

public static String getIPfromURL(String url) {
    if (StringUtils.isBlank(url)) {
        return "";
    }
    URI uri = URI.create(url);
    return uri.getHost();
}

public static int getPortFromUrl(String url) {
    if (url == null || url.length() < 7) {
        return 0;
    } else {
        int s = url.indexOf(":", 7);
        if (s < 0) {
            return 80;
        } else {
            int e = url.indexOf("/", s);
            if (e < 0) {
                e = url.length();
            }
            String port = url.substring(s + 1, e);
            return Integer.parseInt(port);
        }
    }
}


public static boolean isBlankIp(String ip) {
    if (StringUtils.isBlank(ip) || "0.0.0.0".equals(ip.trim())) {
        return true;
    } else {
        return false;
    }
}

public static String addZeroToCpeIp(String ip) {
    if (StringUtils.isBlank(ip) || (ip.equals("..."))) {
        return null;
    } else {
        ip = ip.trim();
    }

    if (ip.indexOf("@") < 0) {
        return IPUtil.addZeroToIP(ip);
    }
    String ip1 = IPUtil.addZeroToIP(ip.substring(0, ip.indexOf(":")));
    String ip2 = ip.substring(ip.indexOf(":") + 1, ip.indexOf("@"));
    String ip3 = IPUtil.addZeroToIP(ip.substring(ip.indexOf("@") + 1, ip.length()));
    String newIp = ip1 + ":" + ip2 + "@" + ip3;
    return newIp;
}

public static String removeZeroFromCpeIp(String ip) {
    if (StringUtils.isBlank(ip) || (ip.equals("..."))) {
        return null;
    } else {
        ip = ip.trim();
    }

    if (ip.indexOf("@") < 0) {
        return removeZeroFromIP(ip);
    }

    String ip1 = removeZeroFromIP(ip.substring(0, ip.indexOf(":")));
    String ip2 = ip.substring(ip.indexOf(":") + 1, ip.indexOf("@"));
    String ip3 = removeZeroFromIP(ip.substring(ip.indexOf("@") + 1, ip.length()));
    String newIp = ip1 + ":" + ip2 + "@" + ip3;
    return newIp;
}

/**
 * IP地址去多余零
 *
 * @param ip String
 * @return String
 */
public static String removeZeroFromIP(String ip) {
    Pattern pattern = Pattern.compile("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}");
    Matcher matcher = pattern.matcher(ip);
    if (!matcher.matches()) {
        return ZEROIP;
    }
    String[] ipSections = ip.split("\\.");
    StringBuffer rtnIp = new StringBuffer("");

    for (int i = 0; i < ipSections.length; i++) {
        String ipSec = ipSections[i];
        while (ipSec.startsWith("0") && (ipSec.length() > 1)) {
            ipSec = ipSec.substring(1);
        }
        rtnIp.append(ipSec).append(".");
    }
    rtnIp.deleteCharAt(rtnIp.length() - 1);
    String s = rtnIp.toString();
    rtnIp.delete(0, rtnIp.length());
    return s;
}

/**
 * IP地址补齐零
 *
 * @param ip String
 * @return String
 */
public static String addZeroToIP(String ip) {
    if (StringUtils.isBlank(ip) || (ip.equals("...")) || (ip.length() == 15)) {
        return ip;
    }

    char[] s = ip.toCharArray();
    char[] sip = {'0', '0', '0', '.', '0', '0', '0', '.', '0', '0', '0', '.', '0', '0', '0'};
    int ileft = 15 - s.length;
    int count = 0;

    for (int i = 14; i >= 0; --i) {
        if (count == 3) {
            count = 0;
            continue;
        }

        if (s[i - ileft] >= '0' && s[i - ileft] <= '9') {
            sip[i] = s[i - ileft];
            count++;
        } else if (s[i - ileft] == '.' && count < 3) {
            count++;
            ileft--;
        }

        if (i == ileft) {
            break;
        }

    }
    return String.valueOf(sip);
}


public static String getIpShow(String ip) {
    if (ip == null) {
        return null;
    }
    if (ip.indexOf("@") < 0) {
        return removeZeroFromIP(ip);
    }
    return removeZeroFromCpeIp(ip);
}

// modified by guolong.zhu

/**
 * <p>
 * 功能描述:将IP地址转换为Long值
 * </p>
 *
 * @param ip IP地址
 * @return
 */
public static long convertIPToLong(String ip) {
    long rtn = 0;
    String[] arr = ip.split("\\.");
    for (int i = 0; i < arr.length; i++) {
        rtn <<= 8;
        rtn += Long.parseLong(arr[i]);
    }
    for (int i = arr.length; i < 4; i++) {
        rtn <<= 8;
    }
    return rtn;
}

/**
 * <p>
 * 功能描述:判断该IP是否有效的IP
 *
 * @param ip 目标IP
 * @return
 */
public static boolean isValidIP(String ip) {
    if (isBlankIp(ip)) {
        return false;
    }
    String iptemp = removeZeroFromIP(ip);
    if (isBlankIp(iptemp)) {
        return false;
    }
    String test = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
    Pattern pattern = Pattern.compile(test);
    Matcher matcher = pattern.matcher(iptemp);
    return matcher.matches();
}

/**
 * <p>
 * 功能描述:获取合法的IP
 *
 * @param ip 目标IP
 * @return
 */
public static String getValidIP(String ip) {
    if (isBlankIp(ip)) {
        return null;
    }
    Pattern pattern = Pattern.compile("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}");
    Matcher matcher = pattern.matcher(ip);
    if (!matcher.matches()) {
        return null;
    }
    String[] arr = ip.split("\\.");
    if (arr == null || arr.length != 4) {
        return null;
    }
    if (Integer.parseInt(arr[0]) == 0) {
        return null;
    }
    StringBuffer buf = new StringBuffer();
    boolean b = false;
    String rtn;
    try {
        for (int i = 0; i < arr.length; i++) {
            if (Integer.parseInt(arr[i]) > 255) {
                b = true;
                break;
            }
            buf.append(".");
            buf.append(Integer.parseInt(arr[i]));
        }
    } catch (Exception e) {
        return null;
    } finally {
        rtn = buf.substring(1);
        buf.delete(0, buf.length());
    }
    if (b) {
        return null;
    }
    return rtn;
}

/**
 * <p>
 * 功能描述:比较两个IP的大小
 *
 * @param ip1 IP地址1
 * @param ip2 IP地址2
 * @return -2――ip地址非法;-1――ip1大于ip2; 0――ip1等于ip2; 1――ip1小于ip2
 */
public static int compareIP(String ip1, String ip2) {
    ip1 = getValidIP(ip1);
    ip2 = getValidIP(ip2);
    if (ip1 == null || ip2 == null) {
        return -2;
    }

    long ipLong1 = convertIPToLong(ip1);
    long ipLong2 = convertIPToLong(ip2);
    if (ipLong1 > ipLong2) {
        return -1;
    } else if (ipLong1 == ipLong2) {
        return 0;
    } else {
        return 1;
    }
}

/**
 * <p>
 * 功能描述:判断某个IP是否落在指定区段内
 *
 * @param beginIp 区段起始IP
 * @param endIp   区段截止IP
 * @param ip      目标IP
 * @return
 */
public static boolean checkIPRegion(String beginIp, String endIp, String ip) {
    boolean flag = false;

    beginIp = getValidIP(beginIp);
    endIp = getValidIP(endIp);
    ip = getValidIP(ip);

    if (beginIp == null || endIp == null || ip == null) {
        return false;
    }

    if (compareIP(beginIp, endIp) < 0) {
        return false;
    }
    // 如果ip不小于beginIp且不大endIp huqiao 2013-12-24
    if (compareIP(beginIp, ip) >= 0 && compareIP(ip, endIp) >= 0) {
        return true;
    }
    // 过大的ip范围会导致方法返回数组过大内存溢出屏蔽掉 huqiao 2013-12-24
    /* String[] ips = getRegionIPs(beginIp, endIp); if (ips != null && ips.length > 0) { for (int i = 0; i <
     * ips.length; i++) { if (ip.equals(ips[i])) { flag = true; break; } } } */
    return flag;
}

/**
 * <p>
 * 功能描述:判断两个IP区段是否有重叠
 *
 * @param beginIp1 区段1起始IP
 * @param endIp1   区段1截止IP
 * @param beginIp2 区段2起始IP
 * @param endIp2   区段2截止IP
 * @return
 */
public static boolean checkOverlap(String beginIp1, String endIp1, String beginIp2, String endIp2) {
    beginIp1 = getValidIP(beginIp1);
    endIp1 = getValidIP(endIp1);
    beginIp2 = getValidIP(beginIp2);
    endIp2 = getValidIP(endIp2);

    if (beginIp1 == null || endIp1 == null || beginIp2 == null || endIp2 == null) {
        return false;
    }

    if (compareIP(beginIp1, endIp1) < 0 || compareIP(beginIp2, endIp2) < 0) {
        return false;
    }

    if ((compareIP(beginIp2, beginIp1) <= 0 && compareIP(beginIp2, endIp1) >= 0)
            || (compareIP(beginIp1, beginIp2) <= 0 && compareIP(beginIp1, endIp2) >= 0)) {
        return true;
    }

    return false;
}

/**
 * 获取本机ip地址
 *
 * @return
 */
public static List<String> getAllHostIp() {
    List<String> allipaddress = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> al = NetworkInterface.getNetworkInterfaces();
        while (al != null && al.hasMoreElements()) {
            NetworkInterface net = al.nextElement();
            Enumeration<InetAddress> address = net.getInetAddresses();
            while (address.hasMoreElements()) {
                InetAddress ip = address.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    if (!"127.0.0.1".equalsIgnoreCase(ip.getHostAddress())) {
                        allipaddress.add(ip.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException e) {
        LOGGER.error("SocketException in method getHostIp");
    }

    return allipaddress;
}

public static String getLocalIp() {
    if (localServerIP == null || localServerIP.length() == 0) {
        Properties props = System.getProperties(); // 获得系统属性集
        String osName = props.getProperty("os.name");
        if (osName != null && osName.toLowerCase().indexOf("windows") >= 0) {
            localServerIP = getWindowsIp();

        } else {
            localServerIP = getUnixLocalIp();
        }
    }
    return localServerIP;
}


public static String getMac() {
    if (mac == null || mac.length() == 0) {
        List<String> macs = getAllMacAddresses();
        if (macs.size() > 0) {
            mac = macs.get(0);
        } else {
            mac = "";
        }
    }
    return mac;
}


public static List<String> getAllMacAddresses() {
    List<String> addresses = new ArrayList<String>();

    StringBuffer sb = new StringBuffer();
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces != null && networkInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = networkInterfaces.nextElement();
            byte[] mac = netInterface.getHardwareAddress();
            if (mac != null && mac.length != 0) {
                sb.delete(0, sb.length());
                for (byte b : mac) {
                    String hexString = Integer.toHexString(b & 0xFF);
                    sb.append((hexString.length() == 1) ? "0" + hexString : hexString);
                }
                addresses.add(sb.toString());
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    sb.delete(0, sb.length());
    return addresses;
}


public static boolean isLocalIp(String ipAddr) {

    if (ipAddr == null || ipAddr.trim().length() == 0 || "127.0.0.1".equals(ipAddr) || "localhost".equals(ipAddr)
            || "0.0.0.0".equals(ipAddr)) {
        return true;
    }

    try {
        Enumeration<NetworkInterface> al = NetworkInterface.getNetworkInterfaces();
        while (al != null && al.hasMoreElements()) {
            NetworkInterface net = al.nextElement();
            Enumeration<InetAddress> address = net.getInetAddresses();
            while (address.hasMoreElements()) {
                InetAddress ip = address.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    if (ipAddr.equals(ip.getHostAddress())) {
                        return true;
                    }
                }
            }
        }
    } catch (SocketException e) {
        LOGGER.error("SocketException in method isLocalIp");
    }

    return false;
}


private static String getWindowsIp() {
    String ip = "";

    try {
        List<InetAddress> list = getLocalHostLANAddress();
        InetAddress addr;
        if (list != null) {
            addr = list.get(0);
        } else {
            addr = InetAddress.getLocalHost();
        }
        // 获得本机IP
        ip = addr.getHostAddress();
    } catch (Exception e) {
        LOGGER.error("Bad IP Address!" + e, e);
    }

    return ip;
}


private static String getUnixLocalIp() {
    String cmd = "hostname -i";
    Runtime run = Runtime.getRuntime();
    // String result = "";
    StringBuilder strBuf = new StringBuilder();
    BufferedInputStream in = null;
    try {
        Process p = run.exec(cmd);
        in = new BufferedInputStream(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String lineStr;
        while ((lineStr = br.readLine()) != null) {
            strBuf.append(lineStr);
        }

        br.close();
    } catch (Exception e) {
        LOGGER.error("ERROR in method getUnixLocalIp");
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.error("ERROR to close BufferedInputStream");
            }
        }
    }
    String ip = strBuf.toString().trim();
    strBuf.delete(0, strBuf.length());
    return ip;
}


private static List<InetAddress> getLocalHostLANAddress() throws UnknownHostException {
    //ArrayList
    // 地址列表
    List<InetAddress> addrList = new ArrayList<InetAddress>();

    try {
        //a
        InetAddress candidateAddress = null;
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces != null && ifaces
                .hasMoreElements(); ) {
            //a
            NetworkInterface iface = ifaces.nextElement();

            //a
            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                //a
                InetAddress inetAddr = inetAddrs.nextElement();
                //a
                if (!inetAddr.isLoopbackAddress()) {
                    //a
                    if (inetAddr.isSiteLocalAddress()) {
                        // 加入列表
                        addrList.add(inetAddr);
                    } else if (candidateAddress == null) {
                        //a
                        candidateAddress = inetAddr;

                    }
                }
            }
        }


        if (candidateAddress != null && addrList.isEmpty()) {
            //a
            addrList.add(candidateAddress);
        }

        //isEmpty()
        if (addrList.isEmpty()) {
            //getLocalHost
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();

            if (jdkSuppliedAddress == null) {
                //throw
                throw new UnknownHostException(
                        "The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            //add
            addrList.add(jdkSuppliedAddress);
        }
        //return
        return addrList;
    } catch (Exception e) {
        //new
        UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address:"
                + e);
        //a
        unknownHostException.initCause(e);
        // throw
        throw unknownHostException;
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值