Example usage for java.net InetAddress isLoopbackAddress

List of usage examples for java.net InetAddress isLoopbackAddress

Introduction

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

Prototype

public boolean isLoopbackAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a loopback address.

Usage

From source file:com.poinsart.votar.VotarMain.java

public String getWifiIp() {
    Enumeration<NetworkInterface> en = null;
    try {/*w w  w  .  java2 s  . c  om*/
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return null;
    }
    while (en.hasMoreElements()) {
        NetworkInterface intf = en.nextElement();
        if (intf.getName().contains("wlan")) {
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                    //Log.d("VotAR Main", inetAddress.getHostAddress());
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    }
    return null;
}

From source file:org.exoplatform.outlook.jcr.ContentLink.java

/**
 * Instantiates a new content link./*from  w  w w . jav a 2 s.c  o  m*/
 *
 * @param jcrService the jcr service
 * @param sessionProviders the session providers
 * @param finder the finder
 * @param organization the organization
 * @param identityRegistry the identity registry
 * @param cacheService the cache service
 * @param params the params
 * @throws ConfigurationException the configuration exception
 */
public ContentLink(RepositoryService jcrService, SessionProviderService sessionProviders, NodeFinder finder,
        OrganizationService organization, IdentityRegistry identityRegistry, CacheService cacheService,
        InitParams params) throws ConfigurationException {
    this.jcrService = jcrService;
    this.sessionProviders = sessionProviders;
    this.finder = finder;
    this.organization = organization;
    this.identityRegistry = identityRegistry;

    this.activeLinks = cacheService.getCacheInstance(LINK_CACHE_NAME);

    if (params != null) {
        PropertiesParam param = params.getPropertiesParam("link-configuration");
        if (param != null) {
            config = Collections.unmodifiableMap(param.getProperties());
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Property parameters link-configuration not found, will use default settings.");
            }
            config = Collections.<String, String>emptyMap();
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Component configuration not found, will use default settings.");
        }
        config = Collections.<String, String>emptyMap();
    }

    StringBuilder restUrl = new StringBuilder();
    String exoBaseUrl = System.getProperty(EXO_BASE_URL);
    if (exoBaseUrl == null || exoBaseUrl.toUpperCase().toLowerCase().startsWith("http://localhost")) {
        // seems we have base URL not set explicitly for the server
        String schema = config.get(CONFIG_SCHEMA);
        if (schema == null || (schema = schema.trim()).length() == 0) {
            schema = "http";
        }

        String host = config.get(CONFIG_HOST);
        if (host == null || host.trim().length() == 0) {
            host = null;
            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (host == null && interfaces.hasMoreElements()) {
                    NetworkInterface nic = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = nic.getInetAddresses();
                    while (host == null && addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (!address.isLoopbackAddress()) {
                            host = address.getHostName();
                        }
                    }
                }
            } catch (SocketException e) {
                // cannot get net interfaces
            }

            if (host == null) {
                try {
                    host = InetAddress.getLocalHost().getHostName();
                } catch (UnknownHostException e) {
                    host = "localhost:8080"; // assume development environment otherwise
                }
            }
        }
        restUrl.append(schema);
        restUrl.append("://");
        restUrl.append(host);
    } else {
        restUrl.append(exoBaseUrl);
    }

    restUrl.append('/');
    restUrl.append(PortalContainer.getCurrentPortalContainerName());
    restUrl.append('/');
    restUrl.append(PortalContainer.getCurrentRestContextName());
    this.restUrl = restUrl.toString();

    LOG.info("Default service URL for content links is " + this.restUrl);
}

From source file:com.terminal.ide.TermService.java

public String getLocalIpAddress() {
    String addr = null;/*  w w  w .  ja v  a 2  s .  c om*/

    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                String ip = inetAddress.getHostAddress().toString();
                if (!inetAddress.isLoopbackAddress()) {
                    if (addr == null || ip.length() < addr.length()) {
                        addr = ip;
                    }
                }
            }
        }

    } catch (SocketException ex) {
        Log.e("SpartacusRex GET LOCAL IP : ", ex.toString());
    }

    if (addr != null) {
        return addr;
    }

    return "127.0.0.1";
}

From source file:de.forsthaus.gui.service.impl.GuiLoginLoggingServiceImpl.java

@Override
public void fillIp2CountryOnceForAppUpdate() {
    final List<SecLoginlog> originList = getAllLogs();

    int count = 0;
    int localCount = 0;
    int checkCount = 0;
    int updateCount = 0;
    int unknownCount = 0;
    int unknownsysCCCount = 0;

    for (final SecLoginlog secLoginlog : originList) {
        count++;//from   ww w  . j  av  a2s.  c om
        // check if no entry exists for this login
        if (secLoginlog.getIp2Country() == null) {

            IpToCountry ipToCountry = null;
            try {
                // try to get a ipToCountry for the IP from the table
                final InetAddress inetAddress = InetAddress.getByName(secLoginlog.getLglIp());

                // Skip a local ip. Therefore is no country to identify.
                if (inetAddress.isLoopbackAddress() || inetAddress.isSiteLocalAddress()) {
                    localCount++;

                    continue;
                }
                checkCount++;

                ipToCountry = getIpToCountryService().getIpToCountry(inetAddress);

                // if found than get the CountryCode object for it and save
                // all
                if (ipToCountry != null) {
                    final String code2 = ipToCountry.getIpcCountryCode2();
                    final CountryCode sysCC = getCountryCodeService().getCountryCodeByCode2(code2);

                    if (sysCC != null) {
                        final Ip2Country ip2 = getIp2CountryService().getNewIp2Country();
                        ip2.setCountryCode(sysCC);

                        // save all
                        getIp2CountryService().saveOrUpdate(ip2);
                        secLoginlog.setIp2Country(ip2);
                        getLoginLoggingService().update(secLoginlog);
                        updateCount++;
                    } else {
                        unknownsysCCCount++;
                    }
                    continue;
                }

            } catch (final UnknownHostException e) {
                try {
                    Messagebox.show(e.getLocalizedMessage());
                } catch (final InterruptedException e1) {
                    throw new RuntimeException(e1);
                }
            }
            unknownCount++;
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info("Ueberpruefte SecLoginlog " + count);
        logger.info("davon localhost: " + localCount);
        logger.info("hostcheck: " + checkCount);
        logger.info("SecLoginlog updates: " + updateCount);
        logger.info("Hosts, denen kein SysCountryCode zugeordnet werden konnte: : " + unknownsysCCCount);
        logger.info("unbekannte Hosts: " + unknownCount);
    }

}

From source file:de.forsthaus.gui.service.impl.GuiLoginLoggingServiceImpl.java

@Override
public int updateIp2CountryFromLookUpHost(List<SecLoginlog> list) {

    int countRec = 0;
    final List<SecLoginlog> originList = list;

    for (final SecLoginlog secLoginlog : originList) {

        if (secLoginlog.getIp2Country() != null) {

            final Ip2Country ip2c = secLoginlog.getIp2Country();

            try {
                // try to get a ipToCountry for the IP from the table
                final InetAddress inetAddress = InetAddress.getByName(secLoginlog.getLglIp());

                // Skip a local ip. Therefore is no country to identify.
                if (inetAddress.isLoopbackAddress() || inetAddress.isSiteLocalAddress()) {
                    continue;
                }// ww  w . j  av  a  2s .c om

                if (StringUtils.isEmpty(ip2c.getI2cCity())) {
                    final IpLocator ipl = getIp2CountryService().hostIpLookUpIp(secLoginlog.getLglIp());
                    // /** For testing on a local tomcat */
                    // IpLocator ipl =
                    // getIp2CountryService().hostIpLookUpIp("95.111.227.104");

                    if (ipl != null) {

                        if (logger.isDebugEnabled()) {
                            logger.debug("hostLookUp resolved for : " + secLoginlog.getLglIp());
                        }

                        ip2c.setI2cCity(ipl.getCity());
                        ip2c.setI2cLatitude(ipl.getLatitude());
                        ip2c.setI2cLongitude(ipl.getLongitude());
                        getIp2CountryService().saveOrUpdate(ip2c);

                        secLoginlog.setIp2Country(ip2c);
                        getLoginLoggingService().saveOrUpdate(secLoginlog);

                        countRec = countRec + 1;
                    }
                }
            } catch (final Exception e) {
                logger.warn("", e);
                continue;
            }

        } else {
            // create a new entry
            final Ip2Country ip2 = getIp2CountryService().getNewIp2Country();

            try {
                // try to get a ipToCountry for the IP from the table
                final InetAddress inetAddress = InetAddress.getByName(secLoginlog.getLglIp());

                // Skip a local ip. Therefore is no country to identify.
                if (inetAddress.isLoopbackAddress() || inetAddress.isSiteLocalAddress()) {
                    continue;
                }

                final IpLocator ipl = getIp2CountryService().hostIpLookUpIp(secLoginlog.getLglIp());
                // /** For testing on a local tomcat */
                // IpLocator ipl =
                // getIp2CountryService().hostIpLookUpIp("95.111.227.104");

                if (ipl != null) {

                    if (logger.isDebugEnabled()) {
                        logger.debug("hostLookUp resolved for : " + secLoginlog.getLglIp());
                    }

                    final CountryCode sysCC = getCountryCodeService()
                            .getCountryCodeByCode2(ipl.getCountryCode());
                    ip2.setCountryCode(sysCC);

                    ip2.setI2cCity(ipl.getCity());
                    ip2.setI2cLatitude(ipl.getLatitude());
                    ip2.setI2cLongitude(ipl.getLongitude());
                    getIp2CountryService().saveOrUpdate(ip2);

                    secLoginlog.setIp2Country(ip2);
                    getLoginLoggingService().saveOrUpdate(secLoginlog);

                    countRec = countRec + 1;
                }

            } catch (final Exception e) {
                logger.warn("", e);
                continue;
            }

        }

    }

    return countRec;

}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Interface method implementation.//  w w  w .j  ava 2  s  .com
 * Also sets the hostName
 * @see JobConfigurationService#setPort(int)
 */
@Override
public void setPort(int port) {
    String hostName = "";
    String ipAddr = "";
    try {
        hostName = InetAddress.getLocalHost().getHostName();
        ipAddr = InetAddress.getLocalHost().getHostAddress();
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        //Iterate through all network interfaces
        while (nets.hasMoreElements()) {
            NetworkInterface netint = (NetworkInterface) nets.nextElement();
            Enumeration<InetAddress> ips = netint.getInetAddresses();
            //Iterate through all IP adddress
            while (ips.hasMoreElements()) {
                InetAddress ip = ips.nextElement();
                //Take the first address which isn't a loopback and is in the local address
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    LOGGER.info("Host IP Address: " + ip.getHostAddress());
                    ipAddr = ip.getHostAddress();
                    break;
                }
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.error("Error while getting hostName ", e);
    } catch (SocketException e) {
        LOGGER.error("Error while getting hostName ", e);
    }
    this.hostName = new JobHost(hostName, ipAddr, port);
}

From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.kubernetes.KubernetesOperationFactory.java

private KubernetesLoadBalancerDescription baseLoadBalancerDescription(String accountName,
        SpinnakerService service) {// w ww  . j  av a2s.c o m
    String address = service.getAddress();
    int port = service.getPort();
    KubernetesLoadBalancerDescription description = new KubernetesLoadBalancerDescription();

    String namespace = KubernetesProviderInterface.getNamespaceFromAddress(address);
    String name = KubernetesProviderInterface.getServiceFromAddress(address);
    Names parsedName = Names.parseName(name);
    description.setApp(parsedName.getApp());
    description.setStack(parsedName.getStack());
    description.setDetail(parsedName.getDetail());

    description.setName(name);
    description.setNamespace(namespace);
    description.setAccount(accountName);

    KubernetesNamedServicePort servicePort = new KubernetesNamedServicePort();
    servicePort.setPort(port);
    servicePort.setTargetPort(port);
    servicePort.setName("http");
    servicePort.setProtocol("TCP");

    if (service instanceof SpinnakerPublicService) {
        SpinnakerPublicService publicService = (SpinnakerPublicService) service;
        String publicAddress = publicService.getPublicAddress();
        InetAddress addr;
        try {
            addr = InetAddress.getByName(publicAddress);
        } catch (UnknownHostException e) {
            throw new HalException(new ProblemBuilder(Problem.Severity.FATAL,
                    "Failed to parse supplied public address: " + e.getMessage()).build());
        }

        if (!(addr.isAnyLocalAddress() || addr.isLoopbackAddress())) {
            description.setLoadBalancerIp(publicService.getPublicAddress());
            description.setServiceType("LoadBalancer");
        }
    }

    List<KubernetesNamedServicePort> servicePorts = new ArrayList<>();
    servicePorts.add(servicePort);
    description.setPorts(servicePorts);

    return description;
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req);
    String credentialsId = creds.getUserID();
    log.debug("credentialsId={}", credentialsId);

    String jcrUserId = req.getParameter("jcrUserId");
    String jcrPath = req.getParameter("jcrPath");
    log.info("jcrUserId={}, jcrPath={}", jcrUserId, jcrPath);

    Session jcrSession = null;// ww w  . j  av  a 2s  .co m
    Session impersonateSession = null;
    Map<String, Object> templateParams = new HashMap<String, Object>();

    try {
        if (creds.getUserID() == null || creds.getUserID().length() == 0) {
            jcrSession = repository.login();
        } else {
            jcrSession = repository.login(creds);
        }
        log.debug("jcrSession={}", jcrSession);
        User user = ((HippoSession) jcrSession).getUser();

        if (user.isSystemUser()) {
            final InetAddress address = InetAddress.getByName(req.getRemoteHost());
            if (!address.isAnyLocalAddress() && !address.isLoopbackAddress()) {
                throw new LoginException();
            }
        }

        templateParams.put("jcrSession", jcrSession);
        templateParams.put("jcrUserId", jcrUserId);
        templateParams.put("jcrPath", jcrPath);

        Credentials impersonateCredentials = new SimpleCredentials(jcrUserId, "".toCharArray());
        impersonateSession = jcrSession.impersonate(impersonateCredentials);
        Privilege[] privileges = getPrivileges(impersonateSession, jcrPath);
        log.info("========= " + ((SimpleCredentials) impersonateCredentials).getUserID() + " ==============");
        Map<String, String> privilegesMap = new HashMap<>();
        for (Privilege p : privileges) {
            privilegesMap.put(p.getName(), "true");
            log.info("p=" + p.getName());
        }
        templateParams.put("privilegesMap", privilegesMap);
        String[] allPermissions = { "jcr:read", "jcr:write", "hippo:author", "hippo:editor", "hippo:admin",
                "jcr:setProperties", "jcr:setAccessControlPolicy", "jcr:addChildNodes",
                "jcr:getAccessControlPolicy", "jcr:removeChildNodes" };

        templateParams.put("allPermissions", allPermissions);

    } catch (LoginException ex) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
        log.error("Error logging in to repository", ex);
    } catch (Exception ex) {
        templateParams.put("exception", ex);
        log.error("Error retrieving permissions", ex);
    } finally {
        try {
            if (jcrSession != null) {
                renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
            }
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        } finally {
            if (jcrSession != null) {
                jcrSession.logout();
            }

            if (impersonateSession != null) {
                impersonateSession.logout();
            }
        }
    }

}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }// w  ww.  j  av a 2 s.c om
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress()
                && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}

From source file:org.ohthehumanity.carrie.CarrieActivity.java

public String getLocalIpAddress() {
    try {/*  w  w  w  .j  a  v a2 s  .co  m*/
        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()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        //Log.e(TAG, ex.toString());
    }
    return "";
}