Example usage for java.net InetAddress getAllByName

List of usage examples for java.net InetAddress getAllByName

Introduction

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

Prototype

public static InetAddress[] getAllByName(String host) throws UnknownHostException 

Source Link

Document

Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.

Usage

From source file:net.sf.jasperreports.phantomjs.InetUtil.java

public static Inet4Address getIPv4Loopback() {
    InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
    //the phantomjs web server module only works with IPv4
    if (loopbackAddress instanceof Inet4Address) {
        return (Inet4Address) loopbackAddress;
    }//from w ww .  ja  va  2  s.c  o m

    try {
        InetAddress[] addresses = InetAddress.getAllByName(loopbackAddress.getHostName());
        for (InetAddress inetAddress : addresses) {
            if (inetAddress instanceof Inet4Address) {
                return (Inet4Address) inetAddress;
            }
        }
    } catch (UnknownHostException e) {
        log.warn("Error while determining loopback addresses for " + loopbackAddress.getHostName(), e);
    }

    try {
        //keep looking for a IPv4 loopback address
        for (Enumeration<NetworkInterface> itfs = NetworkInterface.getNetworkInterfaces(); itfs
                .hasMoreElements();) {
            NetworkInterface itf = itfs.nextElement();
            if (itf.isLoopback()) {
                for (Enumeration<InetAddress> addresses = itf.getInetAddresses(); addresses
                        .hasMoreElements();) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet4Address) {
                        return (Inet4Address) address;
                    }
                }
            }
        }
    } catch (SocketException e) {
        log.warn("Error while listing network interfaces", e);
    }

    return null;
}

From source file:com.bitsofproof.supernode.core.DNSDiscovery.java

@Override
public List<InetSocketAddress> discover() {
    log.trace("Discovering network using DNS seed");
    int n = 0;//from   ww  w.j a  v a  2  s. co m
    List<InetSocketAddress> al = new ArrayList<InetSocketAddress>();
    for (String hostName : seedHosts) {
        log.trace("Obtain addresses from " + hostName);
        InetAddress[] hostAddresses;
        try {
            hostAddresses = InetAddress.getAllByName(hostName);
            for (InetAddress inetAddress : hostAddresses) {
                al.add(new InetSocketAddress(inetAddress, chain.getPort()));
                ++n;
            }
        } catch (UnknownHostException e) {
        }
    }
    Collections.shuffle(al);
    log.trace("Found " + n + " addresses of seed hosts");
    return al;
}

From source file:org.ots.dns.LocalManagedDns.java

@Override
public InetAddress[] lookupAllHostAddr(String s) throws UnknownHostException {
    if (ipPattern.matcher(s).matches()) {
        String ip = s.substring(3).replace('-', '.');
        return InetAddress.getAllByName(ip);
    }/*w ww  .  j a v a 2  s . com*/
    String ipAddress = NameStore.getInstance().get(s);
    if (!StringUtils.isEmpty(ipAddress)) {
        log.debug("\tmatch");
        return InetAddress.getAllByName(ipAddress);
    } else {
        log.debug("\tmiss");
        return defaultDnsImpl.lookupAllHostAddr(s);
    }
}

From source file:com.doculibre.constellio.filters.LocalRequestFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Set<String> acceptedAndDynamicHosts = new HashSet<String>();
    acceptedAndDynamicHosts.addAll(Arrays.asList(ACCEPTED_HOSTS));

    // Solution adapted from http://www.exampledepot.com/egs/java.net/Local.html
    String hostName = InetAddress.getLocalHost().getHostName();
    InetAddress addrs[] = InetAddress.getAllByName(hostName);
    for (InetAddress addr : addrs) {
        String hostAddress = addr.getHostAddress();
        acceptedAndDynamicHosts.add(hostAddress);
    }/*from   w  ww .  j  a v  a 2 s . c  o m*/

    boolean valid;
    if (isIgnoredRequest(request) || isFileRequest(request)) {
        valid = true;
    } else {
        valid = false;
        String remoteHost = request.getRemoteHost();
        for (String acceptedHost : acceptedAndDynamicHosts) {
            if (remoteHost.equals(acceptedHost)) {
                valid = true;
            }
        }
    }

    if (valid) {
        // Pass control on to the next filter
        chain.doFilter(request, response);
    } else {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        throw new ServletException("Cannot send request to a servlet from outside the Web application : "
                + httpRequest.getRequestURL());
    }
}

From source file:com.edmunds.etm.management.util.DnsUtils.java

/**
 * Returns an array of all IP addresses for the given host name.
 * <p/>//from w  w  w .  j  av a 2  s  .  com
 * The host name can either be a machine name or a textual representation of an IP address. If a literal IP address
 * is supplied, only the validity of the address format is checked.
 *
 * @param host       host name or IP address
 * @param retryCount maximum number of times to retry DNS lookups
 * @return array of IP addresses, or {@code null} if no addresses were found
 */
public static InetAddress[] getAddressesByHost(String host, int retryCount) {

    if (StringUtils.isBlank(host)) {
        throw new IllegalArgumentException("Host name is blank");
    }

    InetAddress[] addresses = null;
    for (int i = 0; i < retryCount; i++) {

        try {
            addresses = InetAddress.getAllByName(host.trim());
        } catch (UnknownHostException e) {
            try {
                Thread.sleep(CONNECT_RETRY_WAIT_MILLIS);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
            }
        }
    }

    return addresses;
}

From source file:net.sqs2.omr.session.service.AbstractRemoteExecutorManager.java

public synchronized void connect(String uri, long key, long sessionID) {

    try {//from   w  w  w  .  j a  va2s  .c om
        if (NetworkUtil.isMyAddress(InetAddress.getAllByName(new URI(uri).getHost()))) {
            if (!AbstractTaskTracker.DEBUG_CLUSTER_MODE) {
                return;
            }
        }

        if (this.maximumNumberOfConnections <= this.remoteTaskTrackerMap.size()) {
            Logger.getLogger("executor")
                    .info("num remoteTaskBroders exceeded:" + this.remoteTaskTrackerMap.size());
            return;
        }

        AbstractTaskTracker<T, D> remoteTaskTracker = this.remoteTaskTrackerMap.get(uri);

        if (remoteTaskTracker != null
                && (remoteTaskTracker.isConnected() == false || remoteTaskTracker.getKey() != key)) {
            this.remoteTaskTrackerMap.remove(uri);
            Logger.getLogger("executor").info("Remove old taskTracker=" + uri);
            remoteTaskTracker = null;
        }

        if (remoteTaskTracker == null) {
            Logger.getLogger("executor").info("Create new taskTracker=" + uri);
            remoteTaskTracker = createRemoteTaskTracker(uri, key, sessionID);
        } else {
            //Logger.getLogger("executor").info("Reuse connected taskTracker=" + uri);
        }
    } catch (SocketException ex) {
        Logger.getLogger("executor").severe("SocketException:" + uri);
    } catch (UnknownHostException ex) {
        Logger.getLogger("executor").severe("URISyntaxException:" + uri);
    } catch (URISyntaxException ex) {
        Logger.getLogger("executor").severe("UnknownHostException:" + uri);
    }
}

From source file:com.orange.cloud.servicebroker.filter.securitygroups.domain.Destination.java

public Stream<String> getIPs() {
    try {//  w  w  w  .ja  v a2  s .c o  m
        return Stream.of(InetAddress.getAllByName(host)).map(InetAddress::getHostAddress);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.glite.authz.common.http.JettyAdminServiceCLI.java

/**
 * Parses the hostname command line argument. Checks that the argument is a valid hostname.
 * /*from  w  w  w. ja va2s .  c o  m*/
 * @param hostArgument the command line hostname argument
 * 
 * @return the hostname
 */
private static String parseHost(String hostArgument) {
    try {
        InetAddress[] addresses = InetAddress.getAllByName(hostArgument);
        return addresses[0].getHostName();
    } catch (UnknownHostException e) {
        exit("The host argument is not a valid hostname or IP address", RC_BAD_ARGUMENTS);
    }

    return null;
}

From source file:com.mgmtp.perfload.perfmon.util.PerfMonUtils.java

/**
 * Gets all IP addresses of the localhost.
 * /*ww w  . j a  v  a2s  . co m*/
 * @return an array of {@link InetAddress} objects
 */
public static InetAddress[] getNetworkIPAddresses() throws UnknownHostException {
    InetAddress localhost = InetAddress.getLocalHost();
    return InetAddress.getAllByName(localhost.getCanonicalHostName());
}

From source file:net.sqs2.omr.task.broker.RemoteTaskExecutorManager.java

private TaskBroker createRemoteTaskBroker(String uriString, long remoteKey, long sessionID) {
    try {/*from  w ww  .  j  a v a2 s . c o m*/
        URI uri = new URI(uriString);

        if (NetworkUtil.isMyAddress(InetAddress.getAllByName(uri.getHost()))) {
            return null;
        }

        RemoteSessionService sessionService = (RemoteSessionService) Naming.lookup(uri.toString()); // connect to remote SessionService
        long result = sessionService.ping(remoteKey); // authentication
        if (DEBUG) {
            Logger.getLogger("executor").info("RemoteSessionService.URI=" + uri);
            Logger.getLogger("executor").info("Hello=" + result);
        }
        TaskBroker remoteTaskBroker = new TaskBroker("Remote", this.manager,
                new TaskExecutorEnv(null, sessionService, remoteKey, sessionID));
        return remoteTaskBroker;
    } catch (UnknownHostException ex) {
        Logger.getLogger("executor").severe("UnknownHostException:" + ex.getMessage());
    } catch (SocketException ex) {
        Logger.getLogger("executor").severe("SocketException:" + ex.getMessage());
    } catch (URISyntaxException ex) {
        Logger.getLogger("executor").severe("URISyntaxException:" + ex.getMessage());
    } catch (ConnectException ex) {
        Logger.getLogger("executor").severe("ConnectException:" + ex.getMessage());
    } catch (RemoteException ex) {
        Logger.getLogger("executor").severe("RemoteException:" + ex.getMessage());
    } catch (MalformedURLException ex) {
        Logger.getLogger("executor").severe("MalformedURLException:" + ex.getMessage());
    } catch (NotBoundException ex) {
        Logger.getLogger("executor").severe("NotBoundException:" + ex.getMessage());
    }
    return null;
}