private HttpConnection(Address config, int connectTimeout) throws IOException { this.address = config; /* * Try each of the host's addresses for best behaviour in mixed IPv4/IPv6 * environments. See http://b/2876927 * TODO: add a hidden method so that Socket.tryAllAddresses can does this for us */ Socket socketCandidate = null; /* * For specific proxy ipaddress such as APN access point(wap gateway ip) * could not be resolved as network hostname,then the config.socketHost will * be the string 'not-a-legal-address'. * Try using the address directly. * @mod by spreadsoft b * */ if (config.socketHost.equals("not-a-legal-address") && config.proxy != null && config.proxy.address() != null && config.proxy.type() == Proxy.Type.HTTP) { System.out.println( "The proxy can not be resolved as hostname:" + config.proxy.address().toString() + ",try use the address directly "); try { socketCandidate = new Socket(); socketCandidate.connect((InetSocketAddress) config.proxy.address(), connectTimeout); } catch (IOException e) { System.out.println("The proxy address stil could not be used."); throw e; } } else { InetAddress[] addresses = InetAddress.getAllByName(config.socketHost); for (int i = 0; i < addresses.length; i++) { try { socketCandidate = (config.proxy != null && config.proxy.type() != Proxy.Type.HTTP) ? new Socket(config.proxy) : new Socket(); socketCandidate.connect( new InetSocketAddress(addresses[i], config.socketPort), connectTimeout); break; } catch (IOException e) { if (i == addresses.length - 1) { throw e; } } } } /* @mod by spreadsoft e */ this.socket = socketCandidate; }
/** * Retrieves an array of Strings naming the distinct, known to be valid local InetAddress names * for this machine. The process is to collect and return the union of the following sets: * * <ol> * <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress()) * <li>InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()) * <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostAddress()) * <li>InetAddress.getAllByName(InetAddress.getByName(null).getHostName()) * <li>InetAddress.getByName("loopback").getHostAddress() * <li>InetAddress.getByName("loopback").getHostname() * </ol> * * @return the distinct, known to be valid local InetAddress names for this machine */ public static String[] listLocalInetAddressNames() { InetAddress addr; InetAddress[] addrs; HashSet set; set = new HashSet(); try { addr = InetAddress.getLocalHost(); addrs = InetAddress.getAllByName(addr.getHostAddress()); for (int i = 0; i < addrs.length; i++) { set.add(addrs[i].getHostAddress()); set.add(addrs[i].getHostName()); } addrs = InetAddress.getAllByName(addr.getHostName()); for (int i = 0; i < addrs.length; i++) { set.add(addrs[i].getHostAddress()); set.add(addrs[i].getHostName()); } } catch (Exception e) { } try { addr = InetAddress.getByName(null); addrs = InetAddress.getAllByName(addr.getHostAddress()); for (int i = 0; i < addrs.length; i++) { set.add(addrs[i].getHostAddress()); set.add(addrs[i].getHostName()); } addrs = InetAddress.getAllByName(addr.getHostName()); for (int i = 0; i < addrs.length; i++) { set.add(addrs[i].getHostAddress()); set.add(addrs[i].getHostName()); } } catch (Exception e) { } try { set.add(InetAddress.getByName("loopback").getHostAddress()); set.add(InetAddress.getByName("loopback").getHostName()); } catch (Exception e) { } return (String[]) set.toArray(new String[set.size()]); }
/** * Special Yahoo connect routines. We resolve hostname IP address and try each one until connected * * @param account * @param store * @return * @throws java.net.UnknownHostException */ private static int yahooConnect( Account account, IMAPStore store, boolean specialYahooConnectEnabled) throws UnknownHostException, MessagingException { int connectionAttempts = 0; store.SetIDCommand( "ID (\"vendor\" \"Zimbra\" \"os\" \"Windows XP\" \"os-version\" \"5.1\" \"guid\" \"4062-5711-9195-4050\")"); if (specialYahooConnectEnabled) { InetAddress[] addresses = InetAddress.getAllByName(account.getReceiveHost()); for (InetAddress address : addresses) { try { store.connect(address.getHostAddress(), account.getLoginName(), account.getPassword()); connectionAttempts++; break; } catch (Throwable t) { } } } else { store.connect(account.getReceiveHost(), account.getLoginName(), account.getPassword()); connectionAttempts++; } return connectionAttempts; }
@Override public NameResolution[] resolve(String name) throws UnknownHostException { InetAddress[] addresses = InetAddress.getAllByName(name); NameResolution[] resolutions = new NameResolution[addresses.length]; for (int i = 0; i < addresses.length; i++) resolutions[i] = new NameResolution(addresses[i]); return resolutions; }
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"}) protected Collection<Address> getPossibleAddresses() { final Collection<String> possibleMembers = getMembers(); final Set<Address> possibleAddresses = new HashSet<Address>(); final NetworkConfig networkConfig = config.getNetworkConfig(); for (String possibleMember : possibleMembers) { AddressHolder addressHolder = AddressUtil.getAddressHolder(possibleMember); try { boolean portIsDefined = addressHolder.getPort() != -1 || !networkConfig.isPortAutoIncrement(); int count = portIsDefined ? 1 : maxPortTryCount; int port = addressHolder.getPort() != -1 ? addressHolder.getPort() : networkConfig.getPort(); AddressMatcher addressMatcher = null; try { addressMatcher = AddressUtil.getAddressMatcher(addressHolder.getAddress()); } catch (InvalidAddressException ignore) { EmptyStatement.ignore(ignore); } if (addressMatcher != null) { final Collection<String> matchedAddresses; if (addressMatcher.isIPv4()) { matchedAddresses = AddressUtil.getMatchingIpv4Addresses(addressMatcher); } else { // for IPv6 we are not doing wildcard matching matchedAddresses = Collections.singleton(addressHolder.getAddress()); } for (String matchedAddress : matchedAddresses) { addPossibleAddresses( possibleAddresses, null, InetAddress.getByName(matchedAddress), port, count); } } else { final String host = addressHolder.getAddress(); final InterfacesConfig interfaces = networkConfig.getInterfaces(); if (interfaces.isEnabled()) { final InetAddress[] inetAddresses = InetAddress.getAllByName(host); for (InetAddress inetAddress : inetAddresses) { if (AddressUtil.matchAnyInterface( inetAddress.getHostAddress(), interfaces.getInterfaces())) { addPossibleAddresses(possibleAddresses, host, inetAddress, port, count); } } } else { addPossibleAddresses(possibleAddresses, host, null, port, count); } } } catch (UnknownHostException e) { logger.warning( "Cannot resolve hostname '" + addressHolder.getAddress() + "'. Please make sure host is valid and reachable."); if (logger.isFinestEnabled()) { logger.finest("Error during resolving possible target!", e); } } } possibleAddresses.remove(node.getThisAddress()); return possibleAddresses; }
/** * Checks the internal hostkey database for the given hostkey. If no matching key can be found, * then the hostname is resolved to an IP address and the search is repeated using that IP * address. * * @param hostname the server's hostname, will be matched with all hostname patterns * @param serverHostKeyAlgorithm type of hostkey, either <code>ssh-rsa</code> or <code>ssh-dss * </code> * @param serverHostKey the key blob * @return * <ul> * <li><code>HOSTKEY_IS_OK</code>: the given hostkey matches an entry for the given hostname * <li><code>HOSTKEY_IS_NEW</code>: no entries found for this hostname and this type of * hostkey * <li><code>HOSTKEY_HAS_CHANGED</code>: hostname is known, but with another key of the same * type (man-in-the-middle attack?) * </ul> * * @throws IOException if the supplied key blob cannot be parsed or does not match the given * hostkey type. */ public int verifyHostkey(String hostname, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException { Object remoteKey = null; if ("ssh-rsa".equals(serverHostKeyAlgorithm)) { remoteKey = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey); } else if ("ssh-dss".equals(serverHostKeyAlgorithm)) { remoteKey = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey); } else throw new IllegalArgumentException("Unknown hostkey type " + serverHostKeyAlgorithm); int result = checkKey(hostname, remoteKey); if (result == HOSTKEY_IS_OK) return result; InetAddress[] ipAdresses = null; try { ipAdresses = InetAddress.getAllByName(hostname); } catch (UnknownHostException e) { return result; } for (int i = 0; i < ipAdresses.length; i++) { int newresult = checkKey(ipAdresses[i].getHostAddress(), remoteKey); if (newresult == HOSTKEY_IS_OK) return newresult; if (newresult == HOSTKEY_HAS_CHANGED) result = HOSTKEY_HAS_CHANGED; } return result; }
/** * A function to test the connection * * @throws UnknownHostException * @throws IOException */ public void testConnection() throws UnknownHostException, IOException { InetAddress[] addresses = InetAddress.getAllByName("www.google.com"); for (InetAddress address : addresses) { if (address.isReachable(timeout)) System.out.printf("%s is reachable%n", address); else System.out.printf("%s could not be contacted%n", address); } }
@Override public void start() { long sTime = System.currentTimeMillis(); if (mServer == null) { try { InetAddress[] adds = InetAddress.getAllByName(mHostName); if (adds != null && adds.length > 0) { mIPs = new ArrayList<>(adds.length); for (InetAddress add : adds) mIPs.add(add.getHostAddress()); } } catch (UnknownHostException e) { mError = UNKNOWN_HOST_ERROR; } catch (Exception e) { mError = UNKNOWN_ERROR; } } else { try { mIPs = resolve(mHostName, mServer); } catch (Exception e) { if (mError == SUCCEED) mError = UNKNOWN_ERROR; e.printStackTrace(); } } mDelay = System.currentTimeMillis() - sTime; }
public InetAddress[] findCache(URL announce_url, String hex_hash) { String Hostname; InetAddress[] Caches; /* * Build the hostname for the DNS query: * bt-<short hash>.bt-<announce hash>-<farm>.find-cache.com * * short hash: first four hexadecimal digits of the BitTorrent hash * announce hash: see hashAnnounceURL() * farm: farm name returned by CDP query. */ Hostname = "bt-" + hex_hash.substring(0, 4) + ".bt-" + hashAnnounceURL(announce_url) + "-" + lookupFarm() + CDPDomainName; // System.out.println("findCache(): " + announce_url + " " + hex_hash + " --> " + Hostname); try { Caches = InetAddress.getAllByName(Hostname); } catch (UnknownHostException NoCache) { Caches = new InetAddress[0]; } return Caches; }
// Print IP addresses and network interfaces private static void printIPAddresses() { try { InetAddress localhost = InetAddress.getLocalHost(); System.out.println("Server: IP Address: " + localhost.getHostAddress()); // Just in case this host has multiple IP addresses.... InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null && allMyIps.length > 1) { System.out.println("Server: Full list of IP addresses:"); for (InetAddress allMyIp : allMyIps) { System.out.println(" " + allMyIp); } } } catch (UnknownHostException ex) { System.out.println("Server: Cannot get IP address of local host"); System.out.println("Server: UnknownHostException: " + ex.getMessage()); } try { System.out.println("Server: Full list of network interfaces:"); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); System.out.println(" " + intf.getName() + " " + intf.getDisplayName()); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { System.out.println(" " + enumIpAddr.nextElement().toString()); } } } catch (SocketException ex) { System.out.println("Server: Cannot retrieve network interface list"); System.out.println("Server: UnknownHostException: " + ex.getMessage()); } }
private Address getRequiredMemberAddress() { TcpIpConfig tcpIpConfig = config.getNetworkConfig().getJoin().getTcpIpConfig(); String host = tcpIpConfig.getRequiredMember(); try { AddressHolder addressHolder = AddressUtil.getAddressHolder(host, config.getNetworkConfig().getPort()); if (AddressUtil.isIpAddress(addressHolder.getAddress())) { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } InterfacesConfig interfaces = config.getNetworkConfig().getInterfaces(); if (interfaces.isEnabled()) { InetAddress[] inetAddresses = InetAddress.getAllByName(addressHolder.getAddress()); if (inetAddresses.length > 1) { for (InetAddress inetAddress : inetAddresses) { if (AddressUtil.matchAnyInterface( inetAddress.getHostAddress(), interfaces.getInterfaces())) { return new Address(inetAddress, addressHolder.getPort()); } } } else if (AddressUtil.matchAnyInterface( inetAddresses[0].getHostAddress(), interfaces.getInterfaces())) { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } } else { return new Address(addressHolder.getAddress(), addressHolder.getPort()); } } catch (final Exception e) { logger.warning(e); } return null; }
public static int getID() { int id = -1; try { InetAddress local = InetAddress.getLocalHost(); String hostname = local.getHostName(); InetAddress[] all = InetAddress.getAllByName(hostname); for (int i = 0; i < all.length; i++) { String ip = all[i].getHostAddress(); System.out.println(i + ": " + all[i].getHostName() + " " + ip); if (ip.indexOf("192") > -1) { String sid = ip.substring(ip.length() - 1, ip.length()); id = Integer.parseInt(sid); System.out.println("Found the ID: " + id); } } } catch (UnknownHostException e) { e.printStackTrace(); } if (id < 0) { System.out.println("IP Address not detected properly"); } return id; }
/** * creates a new RemoteOSGiServiceImpl instance. * * @throws IOException in case of IO problems. */ RemoteOSGiServiceImpl() throws IOException { // find out own IP address try { MY_ADDRESS = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName())[0].getHostAddress(); } catch (final Throwable t) { MY_ADDRESS = System.getProperty( "ch.ethz.iks.r_osgi.ip", //$NON-NLS-1$ "127.0.0.1"); //$NON-NLS-1$ } // set the debug switches final BundleContext context = RemoteOSGiActivator.getActivator().getContext(); String prop = context.getProperty(PROXY_DEBUG_PROPERTY); PROXY_DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false; prop = context.getProperty(MSG_DEBUG_PROPERTY); MSG_DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false; prop = context.getProperty(DEBUG_PROPERTY); DEBUG = prop != null ? Boolean.valueOf(prop).booleanValue() : false; if (log != null) { if (PROXY_DEBUG) { log.log(LogService.LOG_INFO, "PROXY DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$ } if (MSG_DEBUG) { log.log(LogService.LOG_INFO, "MESSAGE DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$ } if (DEBUG) { log.log(LogService.LOG_INFO, "INTERNAL DEBUG OUTPUTS ENABLED"); // $NON-NLS-1$ } } else { if (PROXY_DEBUG || MSG_DEBUG || DEBUG) { System.err.println( "WARNING: NO LOG SERVICE PRESENT, DEBUG PROPERTIES HAVE NO EFFECT ..."); //$NON-NLS-1$ PROXY_DEBUG = false; MSG_DEBUG = false; DEBUG = false; } } // set port prop = context.getProperty(R_OSGi_PORT_PROPERTY); R_OSGI_PORT = prop != null ? Integer.parseInt(prop) : 9278; // initialize the transactionID with a random value nextXid = (short) Math.round(Math.random() * Short.MAX_VALUE); // get the package admin final ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName()); if (ref == null) { // TODO: handle this more gracefully throw new RuntimeException( "No package admin service available, R-OSGi terminates."); //$NON-NLS-1$ } pkgAdmin = (PackageAdmin) context.getService(ref); setupTrackers(context); }
public boolean hasMappedEndpoint() { try { InetAddress.getAllByName(address); return this.port > 1; } catch (final UnknownHostException e) { return false; } }
public static void printHost(String hostName) throws UnknownHostException { InetAddress[] amazon = InetAddress.getAllByName(hostName); System.out.println(amazon[0].getHostName()); for (InetAddress address : amazon) { System.out.printf("\tip: %s%n", address.getHostAddress()); } }
public static void main(String[] args) throws Exception { String ip = InetAddress.getLocalHost().getHostAddress(); InetAddress[] ip1 = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); System.out.println(ip); for (InetAddress ipaddress : ip1) { System.out.println(ipaddress.getHostAddress()); } }
/** Returns our IP address and port. ("xxx.xxx.xxx.xxx:1234") */ public static String getLocalIP() { try { InetAddress localHost = InetAddress.getLocalHost(); InetAddress[] all_IPs = InetAddress.getAllByName(localHost.getHostName()); return (all_IPs[0].toString().split("/"))[1] + ":" + Constants.DEFAULT_PORT; } catch (UnknownHostException e) { return "Unknown"; } }
public static boolean call(PageContext pc) throws PageException { try { InetAddress ia = InetAddress.getLocalHost(); InetAddress[] ias = InetAddress.getAllByName(ia.getHostName()); return _call(ias); } catch (UnknownHostException e) { throw Caster.toPageException(e); } }
private static void resolveHostAddresses(String cn, Collection<String> retval) { try { InetAddress[] addresses = InetAddress.getAllByName(cn); for (InetAddress address : addresses) { retval.add(address.getHostAddress()); } } catch (UnknownHostException e) { Dbg.d(e); } }
public final InetAddress[] resolveInetAddresses(String s) { if (s == null) { throw new UnknownHostException("host == null"); } else { return InetAddress.getAllByName(s); } }
/** * Attempts to connects the socket to any of the {@link InetAddress}es the given host name * resolves to. If connection to all addresses fail, the last I/O exception is propagated to the * caller. * * @param sock socket to connect to any of the given addresses * @param host Host name to connect to * @param port the port to connect to * @param localAddress local address * @param localPort local port * @param params HTTP parameters * @throws IOException if an error occurs during the connection * @throws SocketTimeoutException if timeout expires before connecting */ public Socket connectSocket( Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (sock == null) sock = createSocket(); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sock.bind(isa); } int timeout = HttpConnectionParams.getConnectionTimeout(params); InetAddress[] inetadrs = InetAddress.getAllByName(host); List<InetAddress> addresses = new ArrayList<InetAddress>(inetadrs.length); addresses.addAll(Arrays.asList(inetadrs)); Collections.shuffle(addresses); IOException lastEx = null; for (InetAddress remoteAddress : addresses) { try { sock.connect(new InetSocketAddress(remoteAddress, port), timeout); break; } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } catch (IOException ex) { // create new socket sock = new Socket(); // keep the last exception and retry lastEx = ex; } } if (lastEx != null) { throw lastEx; } return sock; } // connectSocket
/** * 根据主IP地址获取子IP列表 * * @param host * @return */ public static List<String> getHostAddress(String host) { List<String> list = new ArrayList<String>(); try { InetAddress[] addresses = InetAddress.getAllByName(host); for (InetAddress address : addresses) { list.add(address.getHostAddress()); } } catch (UnknownHostException e) { logger.error("failed to getHostAddress.", e); } return list; }
public static boolean call(PageContext pc, String hostName) throws PageException { try { InetAddress[] ias = InetAddress.getAllByName(hostName); return _call(ias); } catch (UnknownHostException e) { if (hostName.equalsIgnoreCase("localhost") || hostName.equals("127.0.0.1") || hostName.equalsIgnoreCase("0:0:0:0:0:0:0:1") || hostName.equalsIgnoreCase("::1")) return call(pc); throw Caster.toPageException(e); } }
public static String[] resolveURL(String url) { try { InetAddress[] addresses = InetAddress.getAllByName(url); String[] res = new String[addresses.length]; int i = 0; for (InetAddress addr : addresses) { res[i++] = addr.getHostAddress(); } return res; } catch (UnknownHostException e) { Log.e(TAG, "Could not resolve url " + url + " : " + e.getMessage()); return null; } }
public static void main(String[] args) { try { if (args.length > 0) { String host = args[0]; InetAddress[] addresses = InetAddress.getAllByName(host); for (int i = 0; i < addresses.length; i++) System.out.println(addresses[i]); } else { InetAddress localHostAddress = InetAddress.getLocalHost(); System.out.println(localHostAddress); } } catch (Exception e) { System.out.println("Error: " + e); } }
public void addRoutev6(String network, String device) { String[] v6parts = network.split("/"); boolean included = isAndroidTunDevice(device); // Tun is opened after ROUTE6, no device name may be present try { Inet6Address ip = (Inet6Address) InetAddress.getAllByName(v6parts[0])[0]; int mask = Integer.parseInt(v6parts[1]); mRoutesv6.addIPv6(ip, mask, included); } catch (UnknownHostException e) { VpnStatus.logException(e); } }
/** * Check if a socket is connected to a local address. * * @param socket the socket * @return true if it is */ public static boolean isLocalAddress(Socket socket) throws UnknownHostException { InetAddress test = socket.getInetAddress(); if (test.isLoopbackAddress()) { return true; } InetAddress localhost = InetAddress.getLocalHost(); // localhost.getCanonicalHostName() is very very slow String host = localhost.getHostAddress(); for (InetAddress addr : InetAddress.getAllByName(host)) { if (test.equals(addr)) { return true; } } return false; }
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException { List<InetAddress> addresses = new ArrayList<>(); addresses.addAll(Arrays.asList(InetAddress.getAllByName(hostname))); List<InetAddress> v6Addresses = new ArrayList<>(); for (ListIterator<InetAddress> it = addresses.listIterator(); it.hasNext(); ) { InetAddress next = it.next(); if (next instanceof Inet6Address) { it.remove(); v6Addresses.add(next); } } addresses.addAll(v6Addresses); return addresses; }
private static List<Peer> resolvePeers(List<String> seeds) { List<Peer> peers = new ArrayList<Peer>(); seeds.forEach( host -> { try { InetAddress[] addresses = InetAddress.getAllByName(host); for (InetAddress inetAddress : addresses) { // TODO: For now use only testnet peers.add(new BitcoinPeer(inetAddress, 18333)); } } catch (UnknownHostException e) { // TODO: Log error message } }); return peers; }
public ArrayList<String> nslookup(String hostname) { try { ArrayList<String> result = new ArrayList<String>(); InetAddress[] hosts = InetAddress.getAllByName(hostname); if (hosts.length < 1) return null; for (int i = 0; i < hosts.length; i++) { result.add(hosts[i].getHostAddress()); } return result; } catch (UnknownHostException ex) { return null; } }