Example usage for java.net InetAddress isSiteLocalAddress

List of usage examples for java.net InetAddress isSiteLocalAddress

Introduction

In this page you can find the example usage for java.net InetAddress isSiteLocalAddress.

Prototype

public boolean isSiteLocalAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a site local address.

Usage

From source file:com.aurel.track.prop.ApplicationBean.java

/**
 * Retrieve all non-loopback IP addresses from all network interfaces
 *
 * @return the array of assigned IP numbers
 */// w w w  . ja  v  a 2  s. c o  m
public static InetAddress[] getInetAddress() {
    List<InetAddress> allIPs = new ArrayList<InetAddress>();
    InetAddress[] allAds = null;

    try {
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it
                        // immediately...
                        allIPs.add(inetAddr);
                        continue;
                    } else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily
                        // site-local.
                        // Store it as a candidate to be returned if
                        // site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback
                        // non-site-local addresses as candidates,
                        // only the first. For subsequent iterations,
                        // candidate will be non-null.
                    }
                }
            }
        }

        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost()
        // returns...
        if (allIPs.isEmpty()) {
            allIPs.add(InetAddress.getLocalHost());
        }

        allAds = new InetAddress[allIPs.size()];
        allAds = allIPs.toArray(allAds);

    } catch (Exception uhn) {
        LOGGER.error(
                "An exception occurred trying to get " + "all IP addresses for this host: " + uhn.getMessage());
    }
    return allAds;
}

From source file:org.apache.metron.enrichment.adapters.geo.GeoAdapter.java

@SuppressWarnings("unchecked")
@Override// w  w  w . ja  va2 s .c  o  m
public JSONObject enrich(CacheKey value) {
    JSONObject enriched = new JSONObject();
    if (!resetConnectionIfNecessary()) {
        _LOG.error(
                "Enrichment failure, cannot maintain a connection to JDBC.  Please check connection.  In the meantime, I'm not enriching.");
        return enriched;
    }
    try {
        InetAddress addr = InetAddress.getByName(value.getValue(String.class));
        if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress()
                || addr.isMulticastAddress()
                || !ipvalidator.isValidInet4Address(value.getValue(String.class))) {
            return new JSONObject();
        }
        String locidQuery = "select IPTOLOCID(\"" + value.getValue() + "\") as ANS";
        ResultSet resultSet = statement.executeQuery(locidQuery);
        String locid = null;
        if (resultSet.next()) {
            locid = resultSet.getString("ANS");
        }
        resultSet.close();
        if (locid == null)
            return new JSONObject();
        String geoQuery = "select * from location where locID = " + locid;
        resultSet = statement.executeQuery(geoQuery);
        if (resultSet.next()) {
            enriched.put("locID", resultSet.getString("locID"));
            enriched.put("country", resultSet.getString("country"));
            enriched.put("city", resultSet.getString("city"));
            enriched.put("postalCode", resultSet.getString("postalCode"));
            enriched.put("latitude", resultSet.getString("latitude"));
            enriched.put("longitude", resultSet.getString("longitude"));
            enriched.put("dmaCode", resultSet.getString("dmaCode"));
            enriched.put("location_point", enriched.get("latitude") + "," + enriched.get("longitude"));
        }
        resultSet.close();
    } catch (Exception e) {
        _LOG.error("Enrichment failure: " + e.getMessage(), e);
        return new JSONObject();
    }
    return enriched;
}

From source file:org.apache.metron.enrichment.adapters.geo.GeoLiteDatabase.java

private boolean isIneligibleAddress(String ipStr, InetAddress addr) {
    return addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress()
            || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(ipStr);
}

From source file:io.tilt.minka.domain.NetworkShardIDImpl.java

private InetAddress findSiteAddress(final Config config) {
    InetAddress fallback = null;/*from   w  w  w  . j ava  2s .co m*/
    try {
        final String niName = config.getFollowerUseNetworkInterfase();
        logger.info("{}: Looking for configured network interfase: {}", getClass().getSimpleName(), niName);
        final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            final NetworkInterface ni = nis.nextElement();
            if (niName.contains(ni.getName())) {
                logger.info("{}: Interfase found: {}, looking for a Site address..", getClass().getSimpleName(),
                        ni.getName());
                final Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    final InetAddress ia = ias.nextElement();
                    if (ia.isSiteLocalAddress()) {
                        logger.info("{}: Host site address found: {}:{} with HostName {}",
                                getClass().getSimpleName(), ia.getHostAddress(), config.getBrokerServerPort(),
                                ia.getHostName());
                        return ia;
                    } else {
                        fallback = ia;
                        logger.warn("{}: Specified interfase: {} is not a site address!!, "
                                + "you should specify a non local-only valid interfase !! where's your lan?",
                                getClass().getSimpleName(), ia.getHostAddress());
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("{}: Cannot build shard id value with hostname", getClass().getSimpleName(), e);
    }
    logger.error("{}: Site network interfase not found !", getClass().getSimpleName());
    return fallback;
}

From source file:org.doxu.g2.gwc.crawler.CrawlThread.java

private boolean isAddressBlocked(InetAddress ip) {
    return ip.isLinkLocalAddress() || ip.isLoopbackAddress() || ip.isSiteLocalAddress()
            || ip.isMulticastAddress();/*from  www. j a va  2 s .  com*/
}

From source file:org.geoserver.security.file.LockFile.java

/**
 * Write some info into the lock file //from  w  w w .  j ava2s.  c  o  m
 * hostname, ip, user and lock file path
 * 
 * @param lockFile
 * @throws IOException
 */
protected void writeLockFileContent(File lockFile) throws IOException {

    FileOutputStream out = new FileOutputStream(lockFile);
    Properties props = new Properties();

    try {
        props.store(out, "Locking info");

        String hostname = "UNKNOWN";
        String ip = "UNKNOWN";

        // find some network info
        try {
            hostname = InetAddress.getLocalHost().getHostName();
            InetAddress addrs[] = InetAddress.getAllByName(hostname);
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress())
                    ip = addr.getHostAddress();
            }
        } catch (UnknownHostException ex) {
        }

        props.put("hostname", hostname);
        props.put("ip", ip);
        props.put("location", lockFile.getCanonicalPath());

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        props.put("principal", auth == null ? "UNKNOWN" : auth.getName());

        props.store(out, "Locking info");
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.ebayopensource.scc.track.TrackerClient.java

private InetAddress getInetAddress() {
    Enumeration<NetworkInterface> eni = null;
    try {//from  w  w  w . ja v a  2s .  co m
        eni = NetworkInterface.getNetworkInterfaces();
        while (eni.hasMoreElements()) {
            NetworkInterface n = eni.nextElement();
            Enumeration<InetAddress> eia = n.getInetAddresses();
            while (eia.hasMoreElements()) {
                InetAddress current = eia.nextElement();
                if (current.isSiteLocalAddress()) {
                    return current;
                }
            }
        }
        return InetAddress.getLocalHost();
    } catch (SocketException | UnknownHostException ex) {
        LOGGER.warn("Failed to get IP address.", ex);
        return null;
    }
}

From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java

public static String getLocalIpAddress() {
    String result = "";
    boolean exit = false;
    try {//from  www  .  j  av a  2 s . com
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                //                   if (!inetAddress.isLoopbackAddress() && !(inetAddress.toString().indexOf(":")>=0)) {
                //                       return inetAddress.getHostAddress().toString();
                //                   }
                //                  Log.v("","ip="+inetAddress.getHostAddress()+
                //                        ", name="+intf.getName());
                if (inetAddress.isSiteLocalAddress()) {
                    result = inetAddress.getHostAddress();
                    //                       Log.v("","result="+result+", name="+intf.getName()+"-");
                    if (intf.getName().equals("wlan0")) {
                        exit = true;
                        break;
                    }
                }
            }
            if (exit)
                break;
        }
    } catch (SocketException ex) {
        Log.e(APPLICATION_TAG, ex.toString());
        result = "192.168.0.1";
    }
    //      Log.v("","getLocalIpAddress result="+result);
    if (result.equals(""))
        result = "192.168.0.1";
    return result;
}

From source file:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Converts the passed in siteUrl to be https if not already or not local.
 * //from  www  .j a v a  2 s  .  c  om
 * @param siteUrl The url of a cadmium site.
 * @return The passed in siteUrl or the same url but converted to https.
 */
protected String getSecureBaseUrl(String siteUrl) {
    if (!siteUrl.startsWith("http://") && !siteUrl.startsWith("https://")) {
        siteUrl = "http://" + siteUrl;
    }
    Matcher urlMatcher = URL_PATTERN.matcher(siteUrl);
    if (urlMatcher.matches()) {
        logger.debug("Url matches [{}]", siteUrl);
        boolean local = false;
        try {
            logger.debug("Checking if host [{}] is local", urlMatcher.group(1));
            InetAddress hostAddr = InetAddress.getByName(urlMatcher.group(1));
            local = hostAddr.isLoopbackAddress() || hostAddr.isSiteLocalAddress();
            logger.debug("IpAddress [{}] local: {}", hostAddr.getHostAddress(), local);
        } catch (UnknownHostException e) {
            logger.warn("Hostname not found [" + siteUrl + "]", e);
        }
        if (!local) {
            return siteUrl.replaceFirst("http://", "https://");
        }
    }
    return siteUrl;
}

From source file:org.nebula.framework.core.HeartbeatWorker.java

private void acquireIp() {
    Enumeration<NetworkInterface> net = null;
    try {/*from   w  ww  . ja v  a  2s .co m*/
        net = NetworkInterface.getNetworkInterfaces();

        while (net.hasMoreElements()) {
            NetworkInterface element = net.nextElement();
            Enumeration<InetAddress> addresses = element.getInetAddresses();
            while (addresses.hasMoreElements()) {

                InetAddress ipAddress = addresses.nextElement();
                if (ipAddress instanceof Inet4Address) {

                    if (ipAddress.isSiteLocalAddress()) {
                        ip = ipAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        // ignore
    }
}