Example usage for org.apache.commons.net.util SubnetUtils getInfo

List of usage examples for org.apache.commons.net.util SubnetUtils getInfo

Introduction

In this page you can find the example usage for org.apache.commons.net.util SubnetUtils getInfo.

Prototype

public final SubnetInfo getInfo() 

Source Link

Document

Return a SubnetInfo instance that contains subnet-specific statistics

Usage

From source file:de.yaio.commons.net.IpAddressMatcher.java

/** 
 * checks if the ipAddress matches one of the netmasks from ipList
 * @param ipAddress              ipAddress to check
 * @return                       true/false if it matches netmasks from ipList
 *///w w  w. j  a  v  a2 s . co m
public boolean isInList(final String ipAddress) {
    for (SubnetUtils address : ipList) {
        if (address.getInfo().isInRange(ipAddress)) {
            return true;
        }
    }
    return false;
}

From source file:net.itransformers.topologyviewer.menu.handlers.graphTools.searchMenuHandlers.SearchByIpMenuHandler.java

@Override
public void actionPerformed(ActionEvent e) {

    //                Map<String, Map<String, GraphMLMetadata<G>>> test1 = graphmlLoader();

    //        String key = JOptionPane.showInputDialog(frame, "Choose IP", JOptionPane.QUESTION_MESSAGE);
    final String ip = JOptionPane.showInputDialog(frame, "Enter IP", "Value", JOptionPane.QUESTION_MESSAGE);

    GraphViewerPanel viewerPanel = (GraphViewerPanel) frame.getTabbedPane().getSelectedComponent();
    Set<String> foundVertexes;
    foundVertexes = viewerPanel.FindNodeByKey("RoutePrefixes", new Object() {
        @Override/*from ww w.  j  a  v  a2s. c  om*/
        public boolean equals(Object obj) {
            String s = (String) obj;
            String[] ipRanges = s.split(",");
            for (String ipRangeNotTrimmed : ipRanges) {
                String ipRange = ipRangeNotTrimmed.trim();
                if (ipRange.equals("") || ipRange.equals("0.0.0.0/0"))
                    continue;
                try {
                    SubnetUtils subnet = new SubnetUtils(ipRange);
                    if (subnet.getInfo().isInRange(ip)) {
                        return true;
                    }
                } catch (IllegalArgumentException iae) {
                    logger.error("Can not parse ip or ip range:" + ipRange + ", ip:" + ip);
                    System.out.println("Can not parse ip or ip range:" + ipRange + ", ip:" + ip);
                    iae.printStackTrace();
                    continue;
                }
            }
            return false;
        }
    });
    if (!foundVertexes.isEmpty()) {
        Iterator it = foundVertexes.iterator();
        if (foundVertexes.size() == 1) {
            Object element = it.next();
            System.out.println("Redrawing around " + element.toString());
            viewerPanel.SetPickedState(element.toString());
            viewerPanel.Animator(element.toString());
        } else {
            JOptionPane.showMessageDialog(frame, "Multiple Nodes with ip " + ip + " found :\n" + foundVertexes,
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    } else {
        JOptionPane.showMessageDialog(frame, "Can not find node with ip " + ip, "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:cc.arduino.net.PACSupportMethods.java

public boolean isInNet(String host, String pattern, String mask) throws UnknownHostException {
    SubnetUtils subnetUtils = new SubnetUtils(pattern, mask);
    subnetUtils.setInclusiveHostCount(true);
    return new CIDRUtils(subnetUtils.getInfo().getCidrSignature()).isInRange(host);
}

From source file:it.greenvulcano.gvesb.api.security.JaxRsIdentityInfo.java

@Override
protected boolean subMatchAddressMask(String addressMask) {
    boolean matches = false;

    if (addressMask != null) {

        SubnetUtils subnet = new SubnetUtils(addressMask);
        subnet.setInclusiveHostCount(true);

        matches = subnet.getInfo().isInRange(remoteAddress);
        if (debug) {
            logger.debug("JaxRsIdentityInfo[" + getName() + "]: AddressMask["
                    + subnet.getInfo().getCidrSignature() + ": " + remoteAddress + "] -> " + matches);
        }//w w w . j  a  va2s .co  m

    }
    return matches;
}

From source file:edu.ucsd.crbs.cws.auth.UserIpAddressValidatorImpl.java

/**
 * Compares <b>requestAddress</b> against ipv4 CIDR in <b>cidrAddress</b>
 * @param requestAddress requestAddress ipv4 address of the request
 * @param cidrAddress ipv4 CIDR address// ww w  .  j  av  a 2  s  .c  o m
 * @return true if the <b>requestAddress</b> is within the range of the 
 * <b>cidrAddress</b>, false otherwise
 */
private boolean isIpv4AddressInCidrAddress(InetAddress requestAddress, final String cidrAddress) {
    try {
        SubnetUtils snUtils = new SubnetUtils(cidrAddress);
        return snUtils.getInfo().isInRange(requestAddress.getHostAddress());
    } catch (Exception ex) {
        _log.log(Level.WARNING, "Problems parsing cidr address: {0} and comparing to {1} : {2}",
                new Object[] { cidrAddress, requestAddress.getHostAddress(), ex.getMessage() });
    }
    return false;
}

From source file:it.greenvulcano.gvesb.identity.impl.HTTPIdentityInfo.java

@Override
protected boolean subMatchAddressMask(String addressMask) {
    if (addressMask == null) {
        return false;
    }/*from   www.  j a  v  a  2 s .com*/

    SubnetUtils subnet = new SubnetUtils(addressMask);
    subnet.setInclusiveHostCount(true);

    String address = request.getRemoteAddr();
    boolean res = subnet.getInfo().isInRange(address);
    if (debug) {
        logger.debug("HTTPIdentityInfo[" + getName() + "]: AddressMask[" + subnet.getInfo().getCidrSignature()
                + ": " + address + "] -> " + res);
    }
    return res;
}

From source file:com.pushinginertia.commons.net.IpAddressRange.java

protected IpAddressRange(final String cidrNotation) throws IllegalArgumentException {
    // 1. compute lo/hi addresses from given cidr block
    final SubnetUtils su = new SubnetUtils(cidrNotation);
    su.setInclusiveHostCount(true);/*  www  . j  a  va  2 s . c  o  m*/
    final SubnetUtils.SubnetInfo info = su.getInfo();
    final String loa = info.getLowAddress();
    final String hia = info.getHighAddress();
    info.getCidrSignature();

    // 2. assign values
    this.cidrNotationList = Arrays.asList(cidrNotation);
    this.lowAddress = new IpAddress(loa);
    this.highAddress = new IpAddress(hia);
}

From source file:com.binarybirchtree.filters.IpFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    // Do not block localhost.
    if (request.getRemoteAddr().equals("127.0.0.1")) {
        filterChain.doFilter(request, response);
        return;//from  w  w w.  j av a2 s.co m
    }

    boolean allowed = true;

    // Refuse connections that circumvented Cloudflare.
    // Checking the latest IP from the X-Forwarded-For header on Heroku, since request.getRemoteAddr() seems to return an IP in Heroku's internal network.
    if (!ipIsInList(request.getRemoteAddr(), internalIps) || (getForwardedIp(request, 1) != null
            && !ipIsInList(getForwardedIp(request, 1), bypassCloudflareIps)
            && !ipIsInList(getForwardedIp(request, 1), cloudflareIps)))
        allowed = false;

    if (allowed) {
        // Check if the IP before Cloudflare is blacklisted.
        String proxiedIp = getForwardedIp(request, 2);

        if (proxiedIp != null) {
            for (String ip : blacklistIps) {
                SubnetUtils subnet = new SubnetUtils(ip);
                subnet.setInclusiveHostCount(true);
                if (!subnet.getInfo().isInRange(proxiedIp)) {
                    allowed = false;
                    break;
                }
            }
        }
    }

    // If the request failed one of the tests, send an error response and do not continue processing the request.
    if (!allowed) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    // If the request passed the tests, allow it to be processed normally.
    filterChain.doFilter(request, response);
}

From source file:com.hurence.logisland.processor.MatchIP.java

@Override
protected void updateMatchingRules(ProcessContext context) {
    // loop over dynamic properties to add rules
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }/*w w  w.  j a  v a 2 s .c o m*/

        final String name = entry.getKey().getName();
        final String query = entry.getValue();
        String[] params = query.split(":", 2);
        if (params.length == 2) {
            String queryField = params[0];
            String luceneQuery;
            String luceneValue;
            String ipValue = params[1];
            Matcher ipMatcher = ipPattern.matcher(ipValue);
            Matcher cidrMatcher = cidrPattern.matcher(ipValue);
            if (ipMatcher.lookingAt()) {
                // This is a static ip address
                // convert it to a long
                long addr = ipToLong(ipValue);
                luceneValue = String.valueOf(addr);
                luceneQuery = queryField + ":" + luceneValue;
                matchingRules.put(name, new MatchingRule(name, luceneQuery, query));
                luceneAttrsToQuery.add(queryField);
            } else if (cidrMatcher.lookingAt()) {
                // This is a cidr
                // Convert it to a range
                SubnetUtils su = new SubnetUtils(ipValue);
                String lowIp = su.getInfo().getLowAddress();
                String highIp = su.getInfo().getHighAddress();
                long lowIpLong = ipToLong(lowIp);
                long highIpLong = ipToLong(highIp);
                luceneValue = "[ " + String.valueOf(lowIpLong) + " TO " + String.valueOf(highIpLong) + " ]";
                luceneQuery = queryField + ":" + luceneValue;
                matchingRules.put(name, new MatchingRule(name, luceneQuery, query));
                luceneAttrsToQuery.add(queryField);
            } else {
                regexpMatchingRules.put(name, new MatchingRule(name, query));
                // Consider the value to be a regexp
                // To Be Done
                Pattern ipRegexp = Pattern.compile(ipValue);
                if (ipRegexps == null) {
                    ipRegexps = new HashMap<>();
                }
                if (ipRegexps.containsKey(queryField)) {
                    HashSet<Pair<String, Pattern>> regexpVals = ipRegexps.get(queryField);
                    regexpVals.add(new ImmutablePair<>(name, ipRegexp));
                    ipRegexps.put(queryField, regexpVals);
                } else {
                    HashSet<Pair<String, Pattern>> regexpVals = new HashSet<>();
                    regexpVals.add(new org.apache.commons.lang3.tuple.ImmutablePair<>(name, ipRegexp));
                    ipRegexps.put(queryField, regexpVals);
                }
            }
        }
    }
}

From source file:it.greenvulcano.gvesb.identity.impl.DummyIdentityInfo.java

@Override
protected boolean subMatchAddressMask(String addressMask) {

    if (addressMask == null) {
        return false;
    }//from  w w w . j  ava2s  . c o m

    SubnetUtils subnet = new SubnetUtils(addressMask);
    subnet.setInclusiveHostCount(true);

    boolean res = false;
    String address = null;
    for (String a : addresses) {
        address = a;
        res = subnet.getInfo().isInRange(address);
        System.out.println("[" + address + "] -> " + addressMask + " : " + res);
        if (res) {
            break;
        }
    }
    System.out.println("DummyIdentityInfo[" + getName() + "]: AddressMask["
            + subnet.getInfo().getCidrSignature() + ": " + address + "] -> " + res);
    return res;
}