Example usage for java.net InetAddress getByAddress

List of usage examples for java.net InetAddress getByAddress

Introduction

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

Prototype

public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException 

Source Link

Document

Creates an InetAddress based on the provided host name and IP address.

Usage

From source file:org.apache.hadoop.net.NetUtils.java

/**
 * 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.//from  w ww.j a v  a 2 s  .  c  o  m
 * @param host the hostname or IP use to instantiate the object
 * @param port the port number
 * @return InetSocketAddress
 */
public static InetSocketAddress makeSocketAddr(String host, int port) {
    String staticHost = getStaticResolution(host);
    String resolveHost = (staticHost != null) ? staticHost : host;

    InetSocketAddress addr;
    try {
        InetAddress iaddr = SecurityUtil.getByName(resolveHost);
        // if there is a static entry for the host, make the returned
        // 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;
}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private InetAddress[] resolveInternal(String originalHost, String host) throws IOException {
    if (isValidIpAddress(host))
        return fromAddressString(originalHost, host);
    // First, I'll try to load address cached.
    if (mHostCache.containsKey(host)) {
        final InetAddress[] hostAddr = mHostCache.get(host);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got cached " + Arrays.toString(hostAddr));
        }//w w w.j  a  va 2  s. com
        return hostAddr;
    }
    // Then I'll try to load from custom host mapping.
    // Stupid way to find top domain, but really fast.
    if (mHostMapping.contains(host)) {
        final String mappedAddr = mHostMapping.getString(host, null);
        if (mappedAddr != null) {
            final InetAddress[] hostAddr = fromAddressString(originalHost, mappedAddr);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Got mapped " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
    }
    mSystemHosts.reloadIfNeeded();
    if (mSystemHosts.contains(host)) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, mSystemHosts.getAddress(host));
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got hosts " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    final String customMappedHost = findHost(host);
    if (customMappedHost != null) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, customMappedHost);
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + customMappedHost + " for host " + host);
        }
        return hostAddr;
    }
    // Use TCP DNS Query if enabled.
    final Resolver dns = getResolver();
    if (dns != null && mPreferences.getBoolean(KEY_TCP_DNS_QUERY, false)) {
        final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
        final Record[] records;
        lookup.setResolver(dns);
        lookup.run();
        final int result = lookup.getResult();
        if (result != Lookup.SUCCESSFUL) {
            throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
        }
        records = lookup.getAnswers();
        final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
        // Test each IP address resolved.
        for (final Record record : records) {
            if (record instanceof ARecord) {
                final InetAddress ipv4Addr = ((ARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
            } else if (record instanceof AAAARecord) {
                final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
            }
        }
        if (!resolvedAddresses.isEmpty()) {
            final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
        // No address is reachable, but I believe the IP is correct.

        for (final Record record : records) {
            if (record instanceof CNAMERecord)
                return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString());
        }
    }
    if (Utils.isDebugBuild()) {
        Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host");
    }
    final InetAddress[] defaultAddresses = InetAddress.getAllByName(host);
    mHostCache.put(host, defaultAddresses);
    return defaultAddresses;
}

From source file:org.mariotaku.twidere.util.net.TwidereDns.java

private InetAddress[] fromResolver(String originalHost, String host, int depth) throws IOException {
    final Resolver dns = getResolver();
    final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
    final Record[] records;
    lookup.setResolver(dns);//from w  w w. ja  v  a 2  s.c o m
    lookup.run();
    final int result = lookup.getResult();
    if (result != Lookup.SUCCESSFUL) {
        throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
    }
    records = lookup.getAnswers();
    final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
    // Test each IP address resolved.
    long ttl = -1;
    for (final Record record : records) {
        if (ttl == -1) {
            ttl = record.getTTL();
        }
        if (record instanceof ARecord) {
            final InetAddress ipv4Addr = ((ARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
        } else if (record instanceof AAAARecord) {
            final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
        }
    }
    if (!resolvedAddresses.isEmpty()) {
        final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
        putCache(originalHost, hostAddr, ttl, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            Log.v(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    // No address is reachable, but I believe the IP is correct.

    for (final Record record : records) {
        if (record instanceof CNAMERecord)
            return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString(), depth + 1);
    }
    return null;
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * 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/*from   w ww . j  av  a  2 s. com*/
 *
 * @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);
        // if there is a static entry for the host, make the returned
        // 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;
}

From source file:org.archive.modules.fetcher.FetchDNS.java

protected boolean isQuadAddress(final CrawlURI curi, final String dnsName, final CrawlHost targetHost) {
    boolean result = false;
    Matcher matcher = InetAddressUtil.IPV4_QUADS.matcher(dnsName);
    // If it's an ip no need to do a lookup
    if (matcher == null || !matcher.matches()) {
        return result;
    }/*from  w w  w . j  av  a 2 s.c o m*/

    result = true;
    // Ideally this branch would never be reached: no CrawlURI
    // would be created for numerical IPs
    if (logger.isLoggable(Level.WARNING)) {
        logger.warning("Unnecessary DNS CrawlURI created: " + curi);
    }
    try {
        targetHost.setIP(
                InetAddress.getByAddress(dnsName,
                        new byte[] { (byte) (new Integer(matcher.group(1)).intValue()),
                                (byte) (new Integer(matcher.group(2)).intValue()),
                                (byte) (new Integer(matcher.group(3)).intValue()),
                                (byte) (new Integer(matcher.group(4)).intValue()) }),
                CrawlHost.IP_NEVER_EXPIRES); // Never expire numeric IPs
        curi.setFetchStatus(S_DNS_SUCCESS);
    } catch (UnknownHostException e) {
        logger.log(Level.SEVERE, "Should never be " + e.getMessage(), e);
        setUnresolvable(curi, targetHost);
    }
    return result;
}

From source file:org.apache.hadoop.hbase.master.TestMasterNoCluster.java

/**
 * Test master failover./*from w  ww.  jav a 2  s .c o m*/
 * Start up three fake regionservers and a master.
 * @throws IOException
 * @throws KeeperException
 * @throws InterruptedException
 */
@Test(timeout = 30000)
public void testFailover() throws IOException, KeeperException, InterruptedException, ServiceException {
    final long now = System.currentTimeMillis();
    // Names for our three servers.  Make the port numbers match hostname.
    // Will come in use down in the server when we need to figure how to respond.
    final ServerName sn0 = ServerName.valueOf("0.example.org", 0, now);
    final ServerName sn1 = ServerName.valueOf("1.example.org", 1, now);
    final ServerName sn2 = ServerName.valueOf("2.example.org", 2, now);
    final ServerName[] sns = new ServerName[] { sn0, sn1, sn2 };
    // Put up the mock servers
    final Configuration conf = TESTUTIL.getConfiguration();
    final MockRegionServer rs0 = new MockRegionServer(conf, sn0);
    final MockRegionServer rs1 = new MockRegionServer(conf, sn1);
    final MockRegionServer rs2 = new MockRegionServer(conf, sn2);
    // Put some data into the servers.  Make it look like sn0 has the metaH
    // Put data into sn2 so it looks like it has a few regions for a table named 't'.
    MetaRegionTracker.setMetaLocation(rs0.getZooKeeper(), rs0.getServerName());
    final TableName tableName = TableName.valueOf("t");
    Result[] results = new Result[] {
            MetaMockingUtil.getMetaTableRowResult(
                    new HRegionInfo(tableName, HConstants.EMPTY_START_ROW, HBaseTestingUtility.KEYS[1]),
                    rs2.getServerName()),
            MetaMockingUtil.getMetaTableRowResult(
                    new HRegionInfo(tableName, HBaseTestingUtility.KEYS[1], HBaseTestingUtility.KEYS[2]),
                    rs2.getServerName()),
            MetaMockingUtil.getMetaTableRowResult(
                    new HRegionInfo(tableName, HBaseTestingUtility.KEYS[2], HConstants.EMPTY_END_ROW),
                    rs2.getServerName()) };
    rs1.setNextResults(HRegionInfo.FIRST_META_REGIONINFO.getRegionName(), results);

    // Create master.  Subclass to override a few methods so we can insert mocks
    // and get notification on transitions.  We need to fake out any rpcs the
    // master does opening/closing regions.  Also need to fake out the address
    // of the 'remote' mocked up regionservers.
    CoordinatedStateManager cp = CoordinatedStateManagerFactory
            .getCoordinatedStateManager(TESTUTIL.getConfiguration());
    HMaster master = new HMaster(conf, cp) {
        InetAddress getRemoteInetAddress(final int port, final long serverStartCode)
                throws UnknownHostException {
            // Return different address dependent on port passed.
            if (port > sns.length) {
                return super.getRemoteInetAddress(port, serverStartCode);
            }
            ServerName sn = sns[port];
            return InetAddress.getByAddress(sn.getHostname(), new byte[] { 10, 0, 0, (byte) sn.getPort() });
        }

        @Override
        ServerManager createServerManager(Server master, MasterServices services) throws IOException {
            ServerManager sm = super.createServerManager(master, services);
            // Spy on the created servermanager
            ServerManager spy = Mockito.spy(sm);
            // Fake a successful close.
            Mockito.doReturn(true).when(spy).sendRegionClose((ServerName) Mockito.any(),
                    (HRegionInfo) Mockito.any(), Mockito.anyInt(), (ServerName) Mockito.any(),
                    Mockito.anyBoolean());
            return spy;
        }

        @Override
        protected CatalogTracker createCatalogTracker() throws IOException {
            // Insert a mock for the connection used by the CatalogTracker.  Any
            // regionserver should do.  Use TESTUTIL.getConfiguration rather than
            // the conf from the master; the conf will already have an HConnection
            // associate so the below mocking of a connection will fail.
            HConnection connection = HConnectionTestingUtility.getMockedConnectionAndDecorate(
                    TESTUTIL.getConfiguration(), rs0, rs0, rs0.getServerName(),
                    HRegionInfo.FIRST_META_REGIONINFO);
            return new CatalogTracker(getZooKeeper(), getConfiguration(), connection, this);
        }

        @Override
        void initNamespace() {
        }
    };
    master.start();

    try {
        // Wait till master is up ready for RPCs.
        while (!master.serviceStarted)
            Threads.sleep(10);
        // Fake master that there are regionservers out there.  Report in.
        for (int i = 0; i < sns.length; i++) {
            RegionServerReportRequest.Builder request = RegionServerReportRequest.newBuilder();
            ;
            ServerName sn = ServerName.parseVersionedServerName(sns[i].getVersionedBytes());
            request.setServer(ProtobufUtil.toServerName(sn));
            request.setLoad(ServerLoad.EMPTY_SERVERLOAD.obtainServerLoadPB());
            master.getMasterRpcServices().regionServerReport(null, request.build());
        }
        ZooKeeperWatcher zkw = master.getZooKeeper();
        // Master should now come up.
        while (!master.isInitialized()) {
            // Fake meta is closed on rs0, try several times in case the event is lost
            // due to race with HMaster#assignMeta
            ZKAssign.transitionNodeClosed(zkw, HRegionInfo.FIRST_META_REGIONINFO, sn0, -1);
            Threads.sleep(100);
        }
        assertTrue(master.isInitialized());
    } finally {
        rs0.stop("Test is done");
        rs1.stop("Test is done");
        rs2.stop("Test is done");
        master.stopMaster();
        master.join();
    }
}

From source file:com.groupon.odo.bmp.http.BrowserMobHostNameResolver.java

@Override
public InetAddress resolve(String hostname) throws IOException {
    // BEGIN ODO CHANGES
    // send requests to Odo
    hostname = "127.0.0.1";
    // END ODO CHANGES

    String remapping = remappings.get(hostname);
    if (remapping != null) {
        hostname = remapping;/*from w ww.  j a  va  2 s  .  c om*/
    }

    try {
        return Address.getByAddress(hostname);
    } catch (UnknownHostException e) {
        // that's fine, this just means it's not an IP address and we gotta look it up, which is common
    }

    boolean isCached = this.isCached(hostname);

    Lookup lookup = new Lookup(Name.fromString(hostname), Type.A);
    lookup.setCache(cache);
    lookup.setResolver(resolver);

    Date start = new Date();
    Record[] records = lookup.run();
    Date end = new Date();

    if (records == null || records.length == 0) {
        throw new UnknownHostException(hostname);
    }

    // assembly the addr object
    ARecord a = (ARecord) records[0];
    InetAddress addr = InetAddress.getByAddress(hostname, a.getAddress().getAddress());

    if (!isCached) {
        // TODO: Associate the the host name with the connection. We do this because when using persistent
        // connections there won't be a lookup on the 2nd, 3rd, etc requests, and as such we wouldn't be able to
        // know what IP address we were requesting.
        RequestInfo.get().dns(start, end, addr.getHostAddress());
    } else {
        // if it is a cached hit, we just record zero since we don't want
        // to skew the data with method call timings (specially under load)
        RequestInfo.get().dns(end, end, addr.getHostAddress());
    }

    return addr;
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();/*ww  w  .  j  av  a  2s .c  o m*/
            return client;
        } else {
            // this flowFile is going to a different destination, reset
            // session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).evaluateAttributeExpressions(flowFile)
            .getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:org.apache.james.dnsservice.dnsjava.DNSJavaService.java

@Override
public InetAddress getByName(String host) throws UnknownHostException {
    String name = allowIPLiteral(host);

    try {/*from   w  w w.  j a va 2 s.  c o  m*/
        // Check if its local
        if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName)
                || name.equals(localAddress)) {
            return getLocalHost();
        }

        return org.xbill.DNS.Address.getByAddress(name);
    } catch (UnknownHostException e) {
        Record[] records = lookupNoException(name, Type.A, "A");

        if (records != null && records.length >= 1) {
            ARecord a = (ARecord) records[0];
            return InetAddress.getByAddress(name, a.getAddress().getAddress());
        } else
            throw e;
    }
}

From source file:org.apache.james.dnsservice.dnsjava.DNSJavaService.java

@Override
public InetAddress[] getAllByName(String host) throws UnknownHostException {
    String name = allowIPLiteral(host);
    try {//from w  w w .  ja  v a  2  s  . c  om
        // Check if its local
        if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName)
                || name.equals(localAddress)) {
            return new InetAddress[] { getLocalHost() };
        }

        InetAddress addr = org.xbill.DNS.Address.getByAddress(name);
        return new InetAddress[] { addr };
    } catch (UnknownHostException e) {
        Record[] records = lookupNoException(name, Type.A, "A");

        if (records != null && records.length >= 1) {
            InetAddress[] addrs = new InetAddress[records.length];
            for (int i = 0; i < records.length; i++) {
                ARecord a = (ARecord) records[i];
                addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress());
            }
            return addrs;
        } else
            throw e;
    }
}