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:com.helger.httpclient.NonCachingDnsResolver.java

@Nonnull
public InetAddress[] resolve(@Nonnull final String sHost) throws UnknownHostException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("DNS resolving host '" + sHost + "'");

    Record[] aRecords = null;/*from   ww  w  .  jav a 2 s  .com*/
    try {
        final Lookup aDNSLookup = createLookup(sHost);
        aRecords = aDNSLookup.run();
    } catch (final TextParseException ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Failed to parse host '" + sHost + "'", ex);
    }

    InetAddress[] ret;
    if (aRecords == null || aRecords.length == 0) {
        // E.g. for IP addresses - use system resolution
        ret = InetAddress.getAllByName(sHost);
    } else {
        // Names found
        final ICommonsList<InetAddress> aAddrs = new CommonsArrayList<>();
        for (final Record aRecord : aRecords) {
            if (aRecord instanceof CNAMERecord) {
                // It's a CName - so a name pointing to a name
                // recursively resolve :)
                final InetAddress[] aNested = resolve(((CNAMERecord) aRecord).getAlias().toString());
                if (aNested != null)
                    aAddrs.addAll(aNested);
            } else if (aRecord instanceof ARecord) {
                // It's an address record
                final InetAddress aInetAddress = ((ARecord) aRecord).getAddress();
                aAddrs.add(aInetAddress);
            } else {
                if (LOGGER.isErrorEnabled())
                    LOGGER.info("Unknown record type found for host '" + sHost + "': "
                            + ClassHelper.getClassLocalName(aRecord));
            }
        }
        ret = aAddrs.toArray(new InetAddress[aAddrs.size()]);
    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Return for '" + sHost + "': " + Arrays.toString(ret));
    return ret;
}

From source file:org.ofbiz.passport.util.PassportUtil.java

public static String getEnvPrefixByHost(HttpServletRequest request) {
    String prefix = "test";
    try {/*  www.jav  a2  s.  c o  m*/
        InetAddress[] addresses = InetAddress.getAllByName(request.getServerName());
        for (InetAddress address : addresses) {
            if (address.isAnyLocalAddress() || address.isLinkLocalAddress() || address.isLoopbackAddress()) {
                return prefix;
            }
        }
        prefix = "live";
    } catch (UnknownHostException e) {
        Debug.logError(e.getMessage(), module);
    }
    return prefix;
}

From source file:org.lilyproject.tools.printhost.PrintHostTool.java

@Override
public int run(CommandLine cmd) throws Exception {
    int result = super.run(cmd);
    if (result != 0) {
        return result;
    }//from   w ww  .  ja  va 2 s  . c  o m

    System.out.println("Below we print the detected host name and address.");
    System.out.println("These are used by Lily and Hadoop. For example, this is what is");
    System.out.println("published in ZooKeeper so that other nodes or clients can");
    System.out.println("connect to this node.");
    System.out.println();
    System.out.println("If this shows localhost and 127.0.0.1, adjust your system setup.");
    System.out.println();

    String nameserver = "default";
    if (cmd.hasOption(nameserverOption.getOpt())) {
        nameserver = cmd.getOptionValue(nameserverOption.getOpt());
    }

    System.out.println("Using nameserver: " + nameserver);

    String cn = InetAddress.getLocalHost().getCanonicalHostName();
    System.out.println("Canonical host name: " + cn);

    InetSocketAddress ad = new InetSocketAddress(cn, 1234);
    System.out.println("Address of the canonical host name: " + ad.getAddress().getHostAddress());

    System.out.println();
    System.out.println("If you use the hostname \"" + cn + "\" in your ZooKeeper connection");
    System.out.println("string, it is interesting to know that what ZooKeeper actually does");
    System.out.println("is retrieving all IP addresses of all hosts listed in the ZK connection");
    System.out.println("string, and then it picks one out of these to connect to.");
    System.out.println("These are all the IP-addresses coupled to " + cn + ":");
    InetAddress addrs[] = InetAddress.getAllByName(cn);
    for (InetAddress addr : addrs) {
        System.out.println("  " + addr.getHostAddress());
    }

    return 0;
}

From source file:nl.strohalm.cyclos.utils.WhitelistValidator.java

/**
 * Check if the given request is allowed on the whitelist
 *//*from w ww .  j  ava 2  s .  c o  m*/
public boolean isAllowed(final String host, final String addr) {
    final boolean allowed = isAllowed(addr);
    if (allowed) {
        return true;
    }
    if (ObjectUtils.equals(host, addr)) {
        // Try to resolve the host name to one of the known hosts
        for (final String current : getAllowedHosts()) {
            try {
                // Check if one of the addresses on the whitelisted hosts is the request address
                final InetAddress[] addresses = InetAddress.getAllByName(current);
                for (final InetAddress address : addresses) {
                    if (address.getHostAddress().equals(addr)) {
                        return true;
                    }
                }
            } catch (final UnknownHostException e) {
                // Go on
            }
        }
        return false;
    } else {
        return isAllowed(host);
    }
}

From source file:uk.me.sa.lightswitch.android.net.TestRequestMessage.java

@Before
public void mock() throws Exception {
    mockStatic(Log.class);

    mockStatic(InetAddress.class);
    when(InetAddress.getAllByName("test.node.invalid")).thenReturn(new InetAddress[] { address1 });
    when(InetAddress.getAllByName("test.nodes.invalid"))
            .thenReturn(new InetAddress[] { address1, address2, address3 });
    when(InetAddress.getAllByName("unknown.node.invalid")).thenThrow(new UnknownHostException());
    when(InetAddress.getAllByName("empty.node.invalid")).thenReturn(new InetAddress[0]);

    whenNew(DatagramSocket.class).withAnyArguments().thenReturn(socket);

    mockStatic(System.class);
}

From source file:id.nci.stm_9.HkpKeyServer.java

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];//from w  w w  .  j  a v  a  2  s  . c om
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:org.openintents.openpgp.keyserver.HkpKeyServer.java

private String submitQuery(String request) throws QueryException, HttpError {
    InetAddress ips[];/*from   www . ja  va  2s  .  c om*/
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:uk.me.sa.lightswitch.android.net.RequestMessage.java

private void sendMessageTo(byte[] message, String node) throws RemoteMessageException {
    try {//  w  w w . j a  v  a2  s . c o m
        DatagramSocket s = new DatagramSocket();

        try {
            InetAddress[] addresses = InetAddress.getAllByName(node);
            List<IOException> failed = new ArrayList<IOException>(addresses.length);

            for (InetAddress address : addresses) {
                log.trace("Sending {} bytes to {}", message.length, address);

                try {
                    s.send(new DatagramPacket(message, message.length,
                            new InetSocketAddress(address, SERVICE)));
                } catch (IOException e) {
                    log.warn("Error sending datagram packet", e);
                    failed.add(e);
                }
            }

            if (addresses.length == 0) {
                log.error("No hosts to send to");
                throw new RemoteMessageException(new IllegalArgumentException("No hosts to send to"));
            } else if (failed.size() == addresses.length) {
                log.error("Error sending all datagram packets");
                throw new RemoteMessageException(failed.get(0));
            } else if (!failed.isEmpty()) {
                log.error("Error sending some (but not all) datagram packets");
            }
        } catch (UnknownHostException e) {
            log.error("Error resolving hostname", e);
            throw new RemoteMessageException(e);
        } catch (RuntimeException e) {
            log.error("Error sending request message", e);
            throw new RemoteMessageException(e);
        } finally {
            s.close();
        }
    } catch (SocketException e) {
        log.error("Error creating socket", e);
        throw new RemoteMessageException(e);
    }
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@SuppressWarnings("ReturnOfCollectionOrArrayField")
protected Set<String> getProxyAddresses() throws ServletException {
    long now = System.currentTimeMillis();
    synchronized (this) {
        if (proxyAddresses == null || (lastUpdate + updateInterval) >= now) {
            try {
                proxyAddresses = new HashSet<String>();
                for (InetAddress add : InetAddress.getAllByName(proxyHost)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("proxy address is: " + add.getHostAddress());
                    }/*from w  w w .j  av a  2s  .  c  om*/
                    proxyAddresses.add(add.getHostAddress());
                }
                lastUpdate = now;
            } catch (UnknownHostException e) {
                throw new ServletException("Could not locate " + proxyHost, e);
            }
        }
        return proxyAddresses;
    }
}

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

/**
 * Write some info into the lock file //w w  w  .j a va  2s  .  c  om
 * 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);
    }
}