Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

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

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:io.fabric8.apiman.ManagerApiMicroServiceConfig.java

@PostConstruct
protected void postConstruct() {

    String host = null;/* w  w  w  .  j  av  a2 s .c o  m*/
    try {
        InetAddress initAddress = InetAddress.getByName("ELASTICSEARCH");
        host = initAddress.getCanonicalHostName();
    } catch (UnknownHostException e) {
        log.error("Could not resolve DNS for ELASTICSEARCH, trying ENV settings next.", e);
    }
    String hostAndPort = Systems.getServiceHostAndPort("ELASTICSEARCH", "localhost", "9200");
    String[] hp = hostAndPort.split(":");
    if (host == null) {
        log.info("ELASTICSEARCH host:port is set to " + hostAndPort + " using ENV settings.");
        host = hp[0];
    }
    String protocol = Systems.getEnvVarOrSystemProperty("ELASTICSEARCH_PROTOCOL", "http");
    System.out.println("*** Connecting to Elastic at service " + protocol + "://" + host + ":" + hp[1]);
    log.debug("CONNECTING TO 'elasticsearch' on " + protocol + "://" + host + ":" + hp[1]);
    config = new SystemConfiguration();
    config.setProperty(APIMAN_MANAGER_STORAGE_ES_HOST, host);
    config.setProperty(APIMAN_MANAGER_STORAGE_ES_PORT, hp[1]);
    config.setProperty(APIMAN_MANAGER_STORAGE_ES_PROTOCOL, protocol);
    config.setProperty(APIMAN_MANAGER_STORAGE_ES_CLUSTER_NAME, "elasticsearch");
}

From source file:com.linkedin.pinot.common.response.ServerInstance.java

public ServerInstance(String name, int port, int seq) {
    InetAddress ipAddr = null;/*w w w.  j a  v a2  s.  c  o  m*/

    try {
        ipAddr = InetAddress.getByName(name);
    } catch (UnknownHostException e) {
        LOGGER.error("Unable to fetch IpAddresses for host:" + name, e);
        ipAddr = null;
    }

    _ipAddress = ipAddr;
    _hostname = _ipAddress != null ? _ipAddress.getHostName() : name;
    _port = port;
    _seq = seq;
    _shortHostName = makeShortHostName(_hostname);
}

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from   ww w .  ja v  a 2 s. co  m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:net.testdriven.psiprobe.controllers.WhoisController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<String> lines = null;
    boolean timeout = false;
    String reverseName = null;//from   ww w .j ava  2  s .com

    String theIP = ServletRequestUtils.getStringParameter(request, "ip", null);

    Whois.Response wh = null;
    try {
        wh = Whois.lookup(getDefaultServer(), getDefaultPort(), theIP, getLookupTimeout());
    } catch (IOException e) {
        timeout = true;
    }

    if (wh != null) {
        lines = new ArrayList<>(50);
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new ByteArrayInputStream(wh.getSummary().getBytes())))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }
    }

    if (theIP != null) {
        try {
            reverseName = InetAddress.getByName(theIP).getCanonicalHostName();
        } catch (UnknownHostException e) {
            logger.error("could not run a DNS query on " + theIP);
        }
    }
    return new ModelAndView(getViewName(), "result", lines).addObject("timeout", timeout)
            .addObject("whoisServer",
                    wh != null ? wh.getServer() + ":" + wh.getPort() : defaultServer + ":" + defaultPort)
            .addObject("domainName", reverseName);
}

From source file:com.cazoodle.crawl.DummySSLProtocolSocketFactory.java

private InetAddress getInetAddress(String host) throws UnknownHostException {
    byte[] ip = dnsCache.getValue(host);
    if (ip == null) {
        LOG.debug(host + ": No IP cached, DNS resolving");
        return InetAddress.getByName(host);
    } else {/* www  . j a  va 2 s  .  com*/
        LOG.debug(host + ": IP cached, skip DNS");
        return InetAddress.getByAddress(host, ip);
    }
}

From source file:com.googlecode.jsonrpc4j.spring.JsonStreamServiceExporter.java

/**
 * {@inheritDoc}/*from  www. j  ava 2s . c om*/
 */
@Override
protected void exportService() throws Exception {

    // create a stream server if needed
    if (streamServer == null) {

        // make sure we have a factory
        if (serverSocketFactory == null) {
            serverSocketFactory = ServerSocketFactory.getDefault();
        }

        // create server socket
        ServerSocket serverSocket = serverSocketFactory.createServerSocket(port, backlog,
                InetAddress.getByName(hostName));

        // create the stream server
        streamServer = new StreamServer(getJsonRpcServer(), maxThreads, serverSocket);
        streamServer.setMaxClientErrors(maxClientErrors);
    }

    // start it
    streamServer.start();
}

From source file:io.gravitee.repository.elasticsearch.analytics.spring.ElasticClientFactory.java

private Client createTransportClient() {
    Settings settings = Settings.settingsBuilder().put("cluster.name", configuration.getClusterName()).build();
    TransportClient transportClient = TransportClient.builder().settings(settings).build();

    List<HostAddress> addresses = configuration.getHostsAddresses();

    for (HostAddress address : addresses) {
        try {//  ww w  .  j  a  va  2 s .c  om
            transportClient.addTransportAddress(new InetSocketTransportAddress(
                    InetAddress.getByName(address.getHostname()), address.getPort()));
        } catch (final UnknownHostException uhe) {
            LOGGER.error("Invalid hostname [{}]", address.getHostname());
            throw new IllegalStateException(String.format("Invalid hostname [%s]", address.getHostname()), uhe);
        }
    }

    return transportClient;
}

From source file:net.darkmist.clf.LogParserTest.java

public void testDashes() throws Exception {
    String in = "1.2.3.4 - - [" + LOG_TIME_AS_STR + "] \"GET http://localhost:80/ HTTP/1.1\" - -";
    LogEntry entry = parser.parse(in);//from   w w w  . j  a va  2  s .  c  om

    assertEquals(InetAddress.getByName("1.2.3.4"), entry.getIP());
    assertEquals(null, entry.getIdent());
    assertEquals(null, entry.getUser());
    assertEquals(LOG_TIME_AS_DATE, entry.getDate());
    assertEquals("GET", entry.getMethod());
    assertEquals("http://localhost:80/", entry.getURI());
    assertEquals("HTTP/1.1", entry.getProtocol());
    assertEquals(-1, entry.getStatus());
    assertEquals(0, entry.getSize());
}

From source file:com.hellblazer.jackal.configuration.basic.LocalMulticastConfiguration.java

@Bean(name = "multicastInterface")
public InetAddress multicastInterface() {
    try {//w w w.  ja  v  a 2s  .  c  om
        return InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.edmunds.etm.management.api.HostAddress.java

/**
 * Gets the host name./*from   w  w w  .  j a  va2 s.  co  m*/
 *
 * @return host name
 */
public String getHostName() {
    if (hostName == null) {
        try {
            InetAddress addr = InetAddress.getByName(host);
            hostName = addr.getHostName();
        } catch (UnknownHostException e) {
            hostName = null;
        }
    }
    return hostName;
}