List of usage examples for java.net InetAddress getAllByName
public static InetAddress[] getAllByName(String host) throws UnknownHostException
From source file:com.irccloud.android.HTTPFetcher.java
public void connect() { if (mThread != null && mThread.isAlive()) { return;//from ww w. j av a2 s . c o m } mThread = new Thread(new Runnable() { @Override public void run() { try { if (isCancelled) return; Crashlytics.log(Log.INFO, TAG, "Requesting: " + mURI); int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80); SocketFactory factory = mURI.getProtocol().equals("https") ? getSSLSocketFactory() : SocketFactory.getDefault(); if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) { Crashlytics.log(Log.INFO, TAG, "Connecting to proxy: " + mProxyHost + " port: " + mProxyPort); mSocket = SocketFactory.getDefault().createSocket(mProxyHost, mProxyPort); mThread = new Thread(new Runnable() { @SuppressLint("NewApi") public void run() { http_thread(); } }); mThread.setName("http-stream-thread"); mThread.start(); } else { InetAddress[] addresses = InetAddress.getAllByName(mURI.getHost()); mAddressCount = addresses.length; for (InetAddress address : addresses) { if (mSocket == null && !isCancelled) { if (mSocketThreads.size() >= MAX_THREADS) { Crashlytics.log(Log.INFO, TAG, "Waiting for other HTTP requests to complete before continuing"); while (mSocketThreads.size() >= MAX_THREADS) { Thread.sleep(1000); } } Thread t = new Thread( new ConnectRunnable(factory, new InetSocketAddress(address, port))); mSocketThreads.add(t); mCurrentSocketThreads.add(t); mAttempts++; t.start(); Thread.sleep(300); } else { break; } } } } catch (Exception ex) { ex.printStackTrace(); } } }); mThread.start(); }
From source file:com.spotify.helios.client.DefaultRequestDispatcher.java
/** * Sets up a connection, retrying on connect failure. *//*from www. j a va 2 s.c o m*/ private HttpURLConnection connect(final URI uri, final String method, final byte[] entity, final Map<String, List<String>> headers) throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException { final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS; final int offset = ThreadLocalRandom.current().nextInt(); while (currentTimeMillis() < deadline) { final List<URI> endpoints = endpointSupplier.get(); if (endpoints.isEmpty()) { throw new RuntimeException("failed to resolve master"); } log.debug("endpoint uris are {}", endpoints); // Resolve hostname into IPs so client will round-robin and retry for multiple A records. // Keep a mapping of IPs to hostnames for TLS verification. final List<URI> ipEndpoints = Lists.newArrayList(); final Map<URI, URI> ipToHostnameUris = Maps.newHashMap(); for (final URI hnUri : endpoints) { try { final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost()); for (final InetAddress ip : ips) { final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(), hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment()); ipEndpoints.add(ipUri); ipToHostnameUris.put(ipUri, hnUri); } } catch (UnknownHostException e) { log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e); } } for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) { final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size()); final String fullpath = ipEndpoint.getPath() + uri.getPath(); final String scheme = ipEndpoint.getScheme(); final String host = ipEndpoint.getHost(); final int port = ipEndpoint.getPort(); if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) { throw new HeliosException(String.format( "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"", VALID_PROTOCOLS_STR)); } final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null); AgentProxy agentProxy = null; Deque<Identity> identities = Queues.newArrayDeque(); try { if (scheme.equals("https")) { agentProxy = AgentProxies.newInstance(); for (final Identity identity : agentProxy.list()) { if (identity.getPublicKey().getAlgorithm().equals("RSA")) { // only RSA keys will work with our TLS implementation identities.offerLast(identity); } } } } catch (Exception e) { log.warn("Couldn't get identities from ssh-agent", e); } try { do { final Identity identity = identities.poll(); try { log.debug("connecting to {}", realUri); final HttpURLConnection connection = connect0(realUri, method, entity, headers, ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity); final int responseCode = connection.getResponseCode(); if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED)) && !identities.isEmpty()) { // there was some sort of security error. if we have any more SSH identities to try, // retry with the next available identity log.debug("retrying with next SSH identity since {} failed", identity.getComment()); continue; } return connection; } catch (ConnectException | SocketTimeoutException | UnknownHostException e) { // UnknownHostException happens if we can't resolve hostname into IP address. // UnknownHostException's getMessage method returns just the hostname which is a // useless message, so log the exception class name to provide more info. log.debug(e.toString()); // Connecting failed, sleep a bit to avoid hammering and then try another endpoint Thread.sleep(200); } } while (false); } finally { if (agentProxy != null) { agentProxy.close(); } } } log.warn("Failed to connect, retrying in 5 seconds."); Thread.sleep(5000); } throw new TimeoutException("Timed out connecting to master"); }
From source file:com.qiniu.android.http.ClientConnectionOperator.java
private String[] systemResolv(String domain) throws UnknownHostException { if (dnsResolver == null) { InetAddress[] addresses = InetAddress.getAllByName(domain); String[] x = new String[addresses.length]; for (int i = 0; i < addresses.length; i++) { x[i] = addresses[i].getHostAddress(); }/*from w ww.j av a 2 s . c om*/ return x; } try { return dnsResolver.query(new Domain(domain, true, false, 3600)); } catch (IOException e) { throw new UnknownHostException(e.getMessage()); } }
From source file:com.clustercontrol.ping.factory.RunMonitorPing.java
/** * fping?ping?????<BR>//from www. j a va2 s .co m * @param facilityId Ping?ID()collect?facilityID??? * @return ???????true * @throws HinemosUnknown */ private boolean collectFping(ArrayList<String> facilityList, ArrayList<Integer> priporityList) throws HinemosUnknown { //??? if (m_now != null) { m_nodeDate = m_now.getTime(); } //?????? // hosts[] IP(String ??) // hostsv6[] IPv6(String??) // node IP???? // target nodo? HashSet<String> hosts = new HashSet<String>(); HashSet<String> hostsv6 = new HashSet<String>(); m_Target = new Hashtable<String, String[]>(); String facilityId = null; int version = 4; String[] node; for (int index = 0; index < facilityList.size(); index++) { facilityId = facilityList.get(index); if (facilityId != null && !"".equals(facilityId)) { node = new String[2]; try { // ?? NodeInfo info = new RepositoryControllerBean().getNode(facilityId); //m_log.error(facilityAttrMap.get(FacilityAttributeConstant.IPPROTOCOLNUMBER)); //???????version? if (info.getIpAddressVersion() != null) { version = info.getIpAddressVersion(); } else { version = 4; } if (version == 6) { InetAddress[] ip = InetAddress.getAllByName(info.getIpAddressV6()); if (ip.length != 1) { //IPInetAddress??????1???????? //UnnownHostExcption UnknownHostException e = new UnknownHostException(); m_log.info("collectFping() : " + e.getClass().getSimpleName() + ", " + e.getMessage()); throw e; } node[0] = ip[0].getHostAddress(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hostsv6.add(node[0]); } } else { node[0] = info.getIpAddressV4(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hosts.add(node[0]); } } if (node[0] != null && !node[0].equals("")) { node[1] = info.getNodeName(); //target?????? m_Target.put(facilityId, node); } } catch (FacilityNotFound e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage(); m_messageOrg = e.getMessage(); return false; } catch (UnknownHostException e) { // ??? } } } if (m_reachabilityFping == null) { m_reachabilityFping = new ReachAddressFping(m_runCount, m_runInterval, m_pingTimeout); } boolean result = true; boolean resultTmp = true; //IPv4???fping?? if (hosts.size() != 0) { result = m_reachabilityFping.isReachable(hosts, 4); m_MsgErr = m_reachabilityFping.getM_errMsg(); } //IPv6???fping6?? if (hostsv6.size() != 0) { resultTmp = m_reachabilityFping.isReachable(hostsv6, 6); m_MsgErrV6 = m_reachabilityFping.getM_errMsg(); //??&???? result = result & resultTmp; } return result; }
From source file:com.techcavern.pircbotz.PircBotZ.java
/** * Attempt to connect to the specified IRC server using the supplied * port number, password, and socketFactory. On success a {@link ConnectEvent} * will be dispatched/*from w w w.j a va2 s .c o m*/ * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * @param socketFactory The factory to use for creating sockets, including secure sockets * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ protected void connect() throws IOException, IrcException { synchronized (stateLock) { Utils.addBotToMDC(this); if (isConnected()) throw new IrcException(IrcException.Reason.AlreadyConnected, "Must disconnect from server before connecting again"); if (getState() == State.CONNECTED) throw new RuntimeException( "Bot is not connected but state is State.CONNECTED. This shouldn't happen"); if (configuration.isIdentServerEnabled() && IdentServer.getServer() == null) throw new RuntimeException("UseIdentServer is enabled but no IdentServer has been started"); //Reset capabilities enabledCapabilities = new ArrayList<String>(); // Connect to the server by DNS server InetAddress[] serverAddresses = InetAddress.getAllByName(configuration.getServerHostname()); Exception lastException = null; for (InetAddress curAddress : serverAddresses) { log.debug("Trying address " + curAddress); try { socket = configuration.getSocketFactory().createSocket(curAddress, configuration.getServerPort(), configuration.getLocalAddress(), 0); //No exception, assume successful break; } catch (Exception e) { lastException = e; String debugSuffix = serverAddresses.length == 0 ? "no more servers" : "trying to check another address"; log.debug("Unable to connect to " + configuration.getServerHostname() + " using the IP address " + curAddress.getHostAddress() + ", " + debugSuffix, e); configuration.getListenerManager() .dispatchEvent(new ConnectAttemptFailedEvent<PircBotZ>(this, curAddress, configuration.getServerPort(), configuration.getLocalAddress(), serverAddresses.length)); } } //Make sure were connected if (socket == null || (socket != null && !socket.isConnected())) throw new IOException("Unable to connect to the IRC network " + configuration.getServerHostname() + " (last connection attempt exception attached)", lastException); state = State.CONNECTED; socket.setSoTimeout(configuration.getSocketTimeout()); log.info("Connected to server."); changeSocket(socket); } configuration.getListenerManager().dispatchEvent(new SocketConnectEvent<PircBotZ>(this)); if (configuration.isIdentServerEnabled()) IdentServer.getServer().addIdentEntry(socket.getInetAddress(), socket.getPort(), socket.getLocalPort(), configuration.getLogin()); if (configuration.isCapEnabled()) // Attempt to initiate a CAP transaction. sendCAP().getSupported(); // Attempt to join the server. if (configuration.isWebIrcEnabled()) sendRaw().rawLineNow("WEBIRC " + configuration.getWebIrcPassword() + " " + configuration.getWebIrcUsername() + " " + configuration.getWebIrcHostname() + " " + configuration.getWebIrcAddress().getHostAddress()); if (StringUtils.isNotBlank(configuration.getServerPassword())) sendRaw().rawLineNow("PASS " + configuration.getServerPassword()); sendRaw().rawLineNow("NICK " + configuration.getName()); sendRaw().rawLineNow("USER " + configuration.getLogin() + " 8 * :" + configuration.getRealName()); //Start input to start accepting lines startLineProcessing(); }
From source file:com.wifiafterconnect.ParsedHttpInput.java
public static InetAddress lookupHost(String hostname) { InetAddress inetAddress[];/* w w w . j ava 2 s. c o m*/ try { inetAddress = InetAddress.getAllByName(hostname); } catch (UnknownHostException e) { return null; } for (InetAddress a : inetAddress) { if (a instanceof Inet4Address) return a; } return null; }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
public static List<String> getEndPoints() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"))); String hostname = InetAddress.getLocalHost().getHostName(); InetAddress[] addresses = InetAddress.getAllByName(hostname); ArrayList<String> endPoints = new ArrayList<>(); for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) { ObjectName obj = i.next(); String scheme = mbs.getAttribute(obj, "scheme").toString(); String port = obj.getKeyProperty("port"); for (InetAddress addr : addresses) { String host = addr.getHostAddress(); String ep = scheme + "://" + host + ":" + port; endPoints.add(ep);// ww w . jav a2 s . c o m } } return endPoints; }
From source file:com.titilink.camel.rest.util.OtherUtil.java
/** * ?dns??ip?/*from w w w . j av a 2 s. c om*/ * * @param dnsip --DNS?? * @return String[] --IP? */ public static String[] getDnsIPs(String dnsip) { String ips[]; try { InetAddress ias[] = InetAddress.getAllByName(dnsip); ips = new String[ias.length]; for (int i = 0; i < ias.length; i++) { ips[i] = ias[i].getHostAddress(); ias[i] = null; } } catch (UnknownHostException e) { ips = null; } return ips; }
From source file:org.exist.management.client.JMXServlet.java
/** * Register all known IP-addresses for localhost. *///from w w w . j a v a 2 s . c o m void registerLocalHostAddresses() { // The external IP address of the server try { localhostAddresses.add(InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException ex) { LOG.warn(String.format("Unable to get HostAddress for localhost: %s", ex.getMessage())); } // The configured Localhost addresses try { for (InetAddress address : InetAddress.getAllByName("localhost")) { localhostAddresses.add(address.getHostAddress()); } } catch (UnknownHostException ex) { LOG.warn(String.format("Unable to retrieve ipaddresses for localhost: %s", ex.getMessage())); } if (localhostAddresses.isEmpty()) { LOG.error("Unable to determine addresses for localhost, jmx servlet might be disfunctional."); } }
From source file:org.apache.hadoop.hdfs.fsshellservice.FsShellServiceImpl.java
private void initThriftServer(int port, int maxQueue) { // Setup the Thrift server LOG.info("Setting up Thrift server listening port " + port); TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); TServerTransport serverTransport;//from www . j av a2 s. c o m FsShellService.Processor<FsShellService.Iface> processor = new FsShellService.Processor<FsShellService.Iface>( this); ServerSocket serverSocket_; try { // Make server socket. Use loop-back address to only serve requests // from local clients, in order to prevent ambiguity for commands // of copyFromLocal() and copyToLocal() serverSocket_ = new ServerSocket(port, maxQueue, InetAddress.getAllByName(null)[0]); // Prevent 2MSL delay problem on server restarts serverSocket_.setReuseAddress(true); } catch (IOException ioe) { LOG.error("Could not create ServerSocket on local address ", ioe); return; } serverTransport = new TServerSocket(serverSocket_, clientTimeout); TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport); serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory); tserver = new TThreadPoolServer(serverArgs); }