Search in sources :

Example 26 with InetAddress

use of java.net.InetAddress in project hadoop by apache.

the class NetUtils method createSocketAddrForHost.

/**
   * Create a socket address with the given host and port.  The hostname
   * might be replaced with another host that was set via
   * {@link #addStaticResolution(String, String)}.  The value of
   * hadoop.security.token.service.use_ip will determine whether the
   * standard java host resolver is used, or if the fully qualified resolver
   * is used.
   * @param host the hostname or IP use to instantiate the object
   * @param port the port number
   * @return InetSocketAddress
   */
public static InetSocketAddress createSocketAddrForHost(String host, int port) {
    String staticHost = getStaticResolution(host);
    String resolveHost = (staticHost != null) ? staticHost : host;
    InetSocketAddress addr;
    try {
        InetAddress iaddr = SecurityUtil.getByName(resolveHost);
        // address look like the original given host
        if (staticHost != null) {
            iaddr = InetAddress.getByAddress(host, iaddr.getAddress());
        }
        addr = new InetSocketAddress(iaddr, port);
    } catch (UnknownHostException e) {
        addr = InetSocketAddress.createUnresolved(host, port);
    }
    return addr;
}
Also used : UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress)

Example 27 with InetAddress

use of java.net.InetAddress in project flink by apache.

the class ConnectionUtils method findConnectingAddress.

/**
	 * Finds the local network address from which this machine can connect to the target
	 * address. This method tries to establish a proper network connection to the
	 * given target, so it only succeeds if the target socket address actually accepts
	 * connections. The method tries various strategies multiple times and uses an exponential
	 * backoff timer between tries.
	 * <p>
	 * If no connection attempt was successful after the given maximum time, the method
	 * will choose some address based on heuristics (excluding link-local and loopback addresses.)
	 * <p>
	 * This method will initially not log on info level (to not flood the log while the
	 * backoff time is still very low). It will start logging after a certain time
	 * has passes.
	 *
	 * @param targetAddress The address that the method tries to connect to.
	 * @param maxWaitMillis The maximum time that this method tries to connect, before falling
	 *                       back to the heuristics.
	 * @param startLoggingAfter The time after which the method will log on INFO level.
	 */
public static InetAddress findConnectingAddress(InetSocketAddress targetAddress, long maxWaitMillis, long startLoggingAfter) throws IOException {
    if (targetAddress == null) {
        throw new NullPointerException("targetAddress must not be null");
    }
    if (maxWaitMillis <= 0) {
        throw new IllegalArgumentException("Max wait time must be positive");
    }
    final long startTimeNanos = System.nanoTime();
    long currentSleepTime = MIN_SLEEP_TIME;
    long elapsedTimeMillis = 0;
    final List<AddressDetectionState> strategies = Collections.unmodifiableList(Arrays.asList(AddressDetectionState.LOCAL_HOST, AddressDetectionState.ADDRESS, AddressDetectionState.FAST_CONNECT, AddressDetectionState.SLOW_CONNECT));
    // loop while there is time left
    while (elapsedTimeMillis < maxWaitMillis) {
        boolean logging = elapsedTimeMillis >= startLoggingAfter;
        if (logging) {
            LOG.info("Trying to connect to " + targetAddress);
        }
        // Try each strategy in order
        for (AddressDetectionState strategy : strategies) {
            InetAddress address = findAddressUsingStrategy(strategy, targetAddress, logging);
            if (address != null) {
                return address;
            }
        }
        // we have made a pass with all strategies over all interfaces
        // sleep for a while before we make the next pass
        elapsedTimeMillis = (System.nanoTime() - startTimeNanos) / 1_000_000;
        long toWait = Math.min(maxWaitMillis - elapsedTimeMillis, currentSleepTime);
        if (toWait > 0) {
            if (logging) {
                LOG.info("Could not connect. Waiting for {} msecs before next attempt", toWait);
            } else {
                LOG.debug("Could not connect. Waiting for {} msecs before next attempt", toWait);
            }
            try {
                Thread.sleep(toWait);
            } catch (InterruptedException e) {
                throw new IOException("Connection attempts have been interrupted.");
            }
        }
        // increase the exponential backoff timer
        currentSleepTime = Math.min(2 * currentSleepTime, MAX_SLEEP_TIME);
    }
    // our attempts timed out. use the heuristic fallback
    LOG.warn("Could not connect to {}. Selecting a local address using heuristics.", targetAddress);
    InetAddress heuristic = findAddressUsingStrategy(AddressDetectionState.HEURISTIC, targetAddress, true);
    if (heuristic != null) {
        return heuristic;
    } else {
        LOG.warn("Could not find any IPv4 address that is not loopback or link-local. Using localhost address.");
        return InetAddress.getLocalHost();
    }
}
Also used : IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 28 with InetAddress

use of java.net.InetAddress in project hadoop by apache.

the class TestDNS method getLocalIPAddr.

private InetAddress getLocalIPAddr() throws UnknownHostException {
    String hostname = DNS.getDefaultHost(DEFAULT);
    InetAddress localhost = InetAddress.getByName(hostname);
    return localhost;
}
Also used : InetAddress(java.net.InetAddress)

Example 29 with InetAddress

use of java.net.InetAddress in project hadoop by apache.

the class TestDNS method testRDNS.

/**
   * TestCase: get our local address and reverse look it up
   */
@Test
public void testRDNS() throws Exception {
    InetAddress localhost = getLocalIPAddr();
    try {
        String s = DNS.reverseDns(localhost, null);
        LOG.info("Local reverse DNS hostname is " + s);
    } catch (NameNotFoundException | CommunicationException e) {
        if (!localhost.isLinkLocalAddress() || localhost.isLoopbackAddress()) {
            //these addresses probably won't work with rDNS anyway, unless someone
            //has unusual entries in their DNS server mapping 1.0.0.127 to localhost
            LOG.info("Reverse DNS failing as due to incomplete networking", e);
            LOG.info("Address is " + localhost + " Loopback=" + localhost.isLoopbackAddress() + " Linklocal=" + localhost.isLinkLocalAddress());
        }
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) NameNotFoundException(javax.naming.NameNotFoundException) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Example 30 with InetAddress

use of java.net.InetAddress in project hadoop by apache.

the class TestNetUtils method testResolverUnqualifedFull.

@Test
public void testResolverUnqualifedFull() {
    String host = "host.a.b";
    InetAddress addr = verifyResolve(host, host + ".");
    verifyInetAddress(addr, host, "1.1.1.1");
}
Also used : InetAddress(java.net.InetAddress) Test(org.junit.Test)

Aggregations

InetAddress (java.net.InetAddress)2063 UnknownHostException (java.net.UnknownHostException)377 IOException (java.io.IOException)284 Test (org.junit.Test)272 InetSocketAddress (java.net.InetSocketAddress)240 NetworkInterface (java.net.NetworkInterface)178 ArrayList (java.util.ArrayList)158 SocketException (java.net.SocketException)148 Inet6Address (java.net.Inet6Address)97 HashMap (java.util.HashMap)95 Inet4Address (java.net.Inet4Address)88 Socket (java.net.Socket)73 LinkAddress (android.net.LinkAddress)70 DatagramPacket (java.net.DatagramPacket)67 Token (org.apache.cassandra.dht.Token)67 DatagramSocket (java.net.DatagramSocket)61 RouteInfo (android.net.RouteInfo)56 Map (java.util.Map)55 LinkProperties (android.net.LinkProperties)52 ServerSocket (java.net.ServerSocket)50