Java Code Examples for java.net.InetSocketAddress#isUnresolved()

The following examples show how to use java.net.InetSocketAddress#isUnresolved() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SeedPeersSocks5Dns.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Resolves a hostname via remote DNS over socks5 proxy.
 */
@Nullable
public static InetSocketAddress lookup(Socks5Proxy proxy, InetSocketAddress addr) {
    if (!addr.isUnresolved()) {
        return addr;
    }
    try {
        SocksSocket proxySocket = new SocksSocket(proxy, addr.getHostString(), addr.getPort());
        InetAddress addrResolved = proxySocket.getInetAddress();
        proxySocket.close();
        if (addrResolved != null) {
            log.debug("Resolved " + addr.getHostString() + " to " + addrResolved.getHostAddress());
            return new InetSocketAddress(addrResolved, addr.getPort());
        } else {
            // note: .onion nodes fall in here when proxy is Tor. But they have no IP address.
            // Unfortunately bitcoinj crashes in PeerAddress if it finds an unresolved address.
            log.error("Connected to " + addr.getHostString() + ".  But did not resolve to address.");
        }
    } catch (Exception e) {
        log.warn("Error resolving " + addr.getHostString() + ". Exception:\n" + e.toString());
    }
    return null;
}
 
Example 2
Source File: HostFileManager.java    From big-c with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static InetSocketAddress parseEntry(String type, String fn, String line) {
  try {
    URI uri = new URI("dummy", line, null, null, null);
    int port = uri.getPort() == -1 ? 0 : uri.getPort();
    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), port);
    if (addr.isUnresolved()) {
      LOG.warn(String.format("Failed to resolve address `%s` in `%s`. " +
              "Ignoring in the %s list.", line, fn, type));
      return null;
    }
    return addr;
  } catch (URISyntaxException e) {
    LOG.warn(String.format("Failed to parse `%s` in `%s`. " + "Ignoring in " +
            "the %s list.", line, fn, type));
  }
  return null;
}
 
Example 3
Source File: Server.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public static Server create(final String bindAddress, final int bindPort) throws IllegalArgumentException {

        // Precondition checks
        if (bindPort < 0 || bindPort > MAX_PORT) {
            throw new IllegalArgumentException("Bind port must be between 0 and " + MAX_PORT);
        }

        // Create the inetaddress and ensure it's resolved
        final InetSocketAddress resolvedInetAddress = bindAddress == null ? new InetSocketAddress(bindPort)
                : new InetSocketAddress(bindAddress, bindPort);
        if (resolvedInetAddress.isUnresolved()) {
            throw new IllegalArgumentException("Address \"" + bindAddress + "\" could not be resolved");
        }

        // Create and return a new server instance
        return new Server(resolvedInetAddress);
    }
 
Example 4
Source File: HiveKuduTableInputFormat.java    From HiveKudu-Handler with Apache License 2.0 6 votes vote down vote up
/**
 * This method might seem alien, but we do this in order to resolve the hostnames the same way
 * Hadoop does. This ensures we get locality if Kudu is running along MR/YARN.
 * @param host hostname we got from the master
 * @param port port we got from the master
 * @return reverse DNS'd address
 */
private String reverseDNS(String host, Integer port) {
    LOG.warn("I was called : reverseDNS");
    String location = this.reverseDNSCacheMap.get(host);
    if (location != null) {
        return location;
    }
    // The below InetSocketAddress creation does a name resolution.
    InetSocketAddress isa = new InetSocketAddress(host, port);
    if (isa.isUnresolved()) {
        LOG.warn("Failed address resolve for: " + isa);
    }
    InetAddress tabletInetAddress = isa.getAddress();
    try {
        location = domainNamePointerToHostName(
                DNS.reverseDns(tabletInetAddress, this.nameServer));
        this.reverseDNSCacheMap.put(host, location);
    } catch (NamingException e) {
        LOG.warn("Cannot resolve the host name for " + tabletInetAddress + " because of " + e);
        location = host;
    }
    return location;
}
 
Example 5
Source File: NettyClientBase.java    From tajo with Apache License 2.0 6 votes vote down vote up
public synchronized void connect() throws ConnectException {
  if (isConnected()) return;

  int retries = 0;
  InetSocketAddress address = key.addr;
  if (address.isUnresolved()) {
    address = resolveAddress(address);
  }

  /* do not call await() inside handler */
  ChannelFuture f = doConnect(address).awaitUninterruptibly();

  if (!f.isSuccess()) {
    if (maxRetryNum > 0) {
      doReconnect(address, f, ++retries);
    } else {
      throw makeConnectException(address, f);
    }
  }
}
 
Example 6
Source File: Socks4ProxyHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    String rhost;
    if (raddr.isUnresolved()) {
        rhost = raddr.getHostString();
    } else {
        rhost = raddr.getAddress().getHostAddress();
    }
    return new DefaultSocks4CommandRequest(
            Socks4CommandType.CONNECT, rhost, raddr.getPort(), username != null? username : "");
}
 
Example 7
Source File: DHT.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
public void addDHTNode (String host, int hport) {
	if (!isRunning()) {
		return;
	}
	InetSocketAddress addr = new InetSocketAddress(host, hport);

	if (!addr.isUnresolved() && !AddressUtils.isBogon(addr)) {
		if(!type.PREFERRED_ADDRESS_TYPE.isInstance(addr.getAddress()) || node.getNumEntriesInRoutingTable() > DHTConstants.BOOTSTRAP_IF_LESS_THAN_X_PEERS)
			return;
		RPCServer srv = serverManager.getRandomActiveServer(true);
		if(srv != null)
			srv.ping(addr);
	}

}
 
Example 8
Source File: DnsServerAddresses.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link DnsServerAddresses} that yields only a single {@code address}.
 */
public static DnsServerAddresses singleton(final InetSocketAddress address) {
    if (address == null) {
        throw new NullPointerException("address");
    }
    if (address.isUnresolved()) {
        throw new IllegalArgumentException("cannot use an unresolved DNS server address: " + address);
    }

    return new SingletonDnsServerAddresses(address);
}
 
Example 9
Source File: SecurityUtil.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Construct the service key for a token
 * @param addr InetSocketAddress of remote connection with a token
 * @return "ip:port" or "host:port" depending on the value of
 *          hadoop.security.token.service.use_ip
 */
public static Text buildTokenService(InetSocketAddress addr) {
  String host = null;
  if (useIpForTokenService) {
    if (addr.isUnresolved()) { // host has no ip address
      throw new IllegalArgumentException(
          new UnknownHostException(addr.getHostName())
      );
    }
    host = addr.getAddress().getHostAddress();
  } else {
    host = StringUtils.toLowerCase(addr.getHostName());
  }
  return new Text(host + ":" + addr.getPort());
}
 
Example 10
Source File: Net.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public static InetSocketAddress checkAddress(SocketAddress sa) {
    if (sa == null)
        throw new NullPointerException();
    if (!(sa instanceof InetSocketAddress))
        throw new UnsupportedAddressTypeException(); // ## needs arg
    InetSocketAddress isa = (InetSocketAddress)sa;
    if (isa.isUnresolved())
        throw new UnresolvedAddressException(); // ## needs arg
    InetAddress addr = isa.getAddress();
    if (!(addr instanceof Inet4Address || addr instanceof Inet6Address))
        throw new IllegalArgumentException("Invalid address type");
    return isa;
}
 
Example 11
Source File: SecurityUtil.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Construct the service key for a token
 * @param addr InetSocketAddress of remote connection with a token
 * @return "ip:port" or "host:port" depending on the value of
 *          hadoop.security.token.service.use_ip
 */
public static Text buildTokenService(InetSocketAddress addr) {
  String host = null;
  if (useIpForTokenService) {
    if (addr.isUnresolved()) { // host has no ip address
      throw new IllegalArgumentException(
          new UnknownHostException(addr.getHostName())
      );
    }
    host = addr.getAddress().getHostAddress();
  } else {
    host = StringUtils.toLowerCase(addr.getHostName());
  }
  return new Text(host + ":" + addr.getPort());
}
 
Example 12
Source File: ClusterAddressUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 将集群地址转换为InetSocketAddress的列表
 *
 * @author sxp
 * @since 2018/7/10
 */
private static List<InetSocketAddress> getAddressesByList(List<String> addressList) {
  List<InetSocketAddress> result = new ArrayList<InetSocketAddress>();

  String host;
  int port;

  for (String address : addressList) {
    if (StringUtils.isEmpty(address)) {
      continue;
    }
    try {
      host = getHost(address);
      port = getPort(address);
      if (StringUtils.isEmpty(host)) {
        continue;
      }

      InetSocketAddress inetAddress = new InetSocketAddress(host, port);

      if (inetAddress.isUnresolved()) {
        continue;
      } else {
        result.add(inetAddress);
      }
    } catch (Throwable t) {
      continue;
    }
  }

  return result;
}
 
Example 13
Source File: ForwardedHeadersFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
	ServerHttpRequest request = exchange.getRequest();
	HttpHeaders original = input;
	HttpHeaders updated = new HttpHeaders();

	// copy all headers except Forwarded
	original.entrySet().stream().filter(
			entry -> !entry.getKey().toLowerCase().equalsIgnoreCase(FORWARDED_HEADER))
			.forEach(entry -> updated.addAll(entry.getKey(), entry.getValue()));

	List<Forwarded> forwardeds = parse(original.get(FORWARDED_HEADER));

	for (Forwarded f : forwardeds) {
		updated.add(FORWARDED_HEADER, f.toHeaderValue());
	}

	// TODO: add new forwarded
	URI uri = request.getURI();
	String host = original.getFirst(HttpHeaders.HOST);
	Forwarded forwarded = new Forwarded().put("host", host).put("proto",
			uri.getScheme());

	InetSocketAddress remoteAddress = request.getRemoteAddress();
	if (remoteAddress != null) {
		// If remoteAddress is unresolved, calling getHostAddress() would cause a
		// NullPointerException.
		String forValue = remoteAddress.isUnresolved() ? remoteAddress.getHostName()
				: remoteAddress.getAddress().getHostAddress();
		int port = remoteAddress.getPort();
		if (port >= 0) {
			forValue = forValue + ":" + port;
		}
		forwarded.put("for", forValue);
	}
	// TODO: support by?

	updated.add(FORWARDED_HEADER, forwarded.toHeaderValue());

	return updated;
}
 
Example 14
Source File: CreateUnresolved.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    InetSocketAddress a = InetSocketAddress.createUnresolved("unresolved", 1234);
    if (!a.isUnresolved())
        throw new RuntimeException("Address is not flagged as 'unresolved'");
}
 
Example 15
Source File: CreateUnresolved.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    InetSocketAddress a = InetSocketAddress.createUnresolved("unresolved", 1234);
    if (!a.isUnresolved())
        throw new RuntimeException("Address is not flagged as 'unresolved'");
}
 
Example 16
Source File: CreateUnresolved.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    InetSocketAddress a = InetSocketAddress.createUnresolved("unresolved", 1234);
    if (!a.isUnresolved())
        throw new RuntimeException("Address is not flagged as 'unresolved'");
}
 
Example 17
Source File: SocketServer.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
/**
 * start up the server socket and when a new connection is received, check that
 * the source address is in our permitted list and if so, start a new console input
 * on that socket.
 */
@Override
public void run()
{
	int threadNum = 1;
	System.out.println("Telnet server started. Listening on port: " + serverSocket.getLocalPort());

	while( true ) {
		try {
			Socket socket = serverSocket.accept();

			InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();

			if( addr.isUnresolved() || ! isAllowed(addr) ) {
				System.out.println("TelnetUI: rejecting connection from: " + addr + " as address is not allowed");
				socket.close();
			}
			else {
				System.out.println("TelnetUI: accepting connection from: " + addr);
				int loginAttempts = 0;

				while( true ) {
					// TODO: might want to put this in another thread so the port doesnt block while the user logs in

					//System.out.println("TelnetUI: starting login" );

					UserProfile profile = login( socket.getInputStream(), socket.getOutputStream() );

					//System.out.println("TelnetUI: login profile obtained" );

					if( profile != null ) {

						//System.out.println("TelnetUI: creating console input" );

						ui.createNewConsoleInput("Telnet Console " + threadNum++, socket.getInputStream(), new PrintStream(socket.getOutputStream()), profile);
						break;
					}

					//System.out.println("TelnetUI: failed to obtain login profile" );

					loginAttempts++;

					if( loginAttempts >= maxLoginAttempts ) {
						System.out.println("TelnetUI: rejecting connection from: " + addr + " as number of failed connections > max login attempts (" + maxLoginAttempts + ")");
						socket.close();
						break;
					}
				}
			}
		}
		catch (Throwable t) {
			t.printStackTrace();
			break;
		}
	}
}
 
Example 18
Source File: AbstractArmeriaCentralDogmaBuilder.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@link EndpointGroup} this client will connect to, derived from {@link #hosts()}.
 *
 * @throws UnknownHostException if failed to resolve the host names from the DNS servers
 */
protected final EndpointGroup endpointGroup() throws UnknownHostException {
    final Set<InetSocketAddress> hosts = hosts();
    checkState(!hosts.isEmpty(), "no hosts were added.");

    final InetSocketAddress firstHost = Iterables.getFirst(hosts, null);
    if (hosts.size() == 1 && !firstHost.isUnresolved()) {
        return toResolvedHostEndpoint(firstHost);
    }

    final List<Endpoint> staticEndpoints = new ArrayList<>();
    final List<EndpointGroup> groups = new ArrayList<>();
    for (final InetSocketAddress addr : hosts) {
        if (addr.isUnresolved()) {
            groups.add(DnsAddressEndpointGroup.builder(addr.getHostString())
                                              .eventLoop(clientFactory.eventLoopGroup().next())
                                              .port(addr.getPort())
                                              .build());
        } else {
            staticEndpoints.add(toResolvedHostEndpoint(addr));
        }
    }

    if (!staticEndpoints.isEmpty()) {
        groups.add(EndpointGroup.of(staticEndpoints));
    }

    final EndpointGroup group;
    if (groups.size() == 1) {
        group = groups.get(0);
    } else {
        group = new CompositeEndpointGroup(groups, EndpointSelectionStrategy.roundRobin());
    }

    if (group instanceof DynamicEndpointGroup) {
        // Wait until the initial endpointGroup list is ready.
        try {
            group.whenReady().get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            final UnknownHostException cause = new UnknownHostException(
                    "failed to resolve any of: " + hosts);
            cause.initCause(e);
            throw cause;
        }
    }

    if (!healthCheckInterval.isZero()) {
        return HealthCheckedEndpointGroup.builder(group, HttpApiV1Constants.HEALTH_CHECK_PATH)
                                         .clientFactory(clientFactory)
                                         .protocol(isUseTls() ? SessionProtocol.HTTPS
                                                              : SessionProtocol.HTTP)
                                         .retryInterval(healthCheckInterval)
                                         .build();
    } else {
        return group;
    }
}
 
Example 19
Source File: CreateUnresolved.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
    InetSocketAddress a = InetSocketAddress.createUnresolved("unresolved", 1234);
    if (!a.isUnresolved())
        throw new RuntimeException("Address is not flagged as 'unresolved'");
}
 
Example 20
Source File: NetUtils.java    From flink with Apache License 2.0 3 votes vote down vote up
/**
 * Encodes an IP address and port to be included in URL. in particular, this method makes
 * sure that IPv6 addresses have the proper formatting to be included in URLs.
 *
 * @param address The socket address with the IP address and port.
 * @return The proper URL string encoded IP address and port.
 */
public static String socketAddressToUrlString(InetSocketAddress address) {
	if (address.isUnresolved()) {
		throw new IllegalArgumentException("Address cannot be resolved: " + address.getHostString());
	}
	return ipAddressAndPortToUrlString(address.getAddress(), address.getPort());
}