Java Code Examples for java.net.InetAddress#getAllByName()

The following examples show how to use java.net.InetAddress#getAllByName() . These examples are extracted from open source projects. 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
private static byte[] getThisHostIPV6Address(String hostName)
        throws Exception {
    InetAddress[] thisHostIPAddresses = null;
    try {
        thisHostIPAddresses = InetAddress.getAllByName(InetAddress
                .getLocalHost().getHostName());
    } catch (UnknownHostException uhEx) {
        uhEx.printStackTrace();
        throw uhEx;
    }
    byte[] thisHostIPV6Address = null;
    for (InetAddress inetAddress : thisHostIPAddresses) {
        if (inetAddress instanceof Inet6Address) {
            if (inetAddress.getHostName().equals(hostName)) {
                thisHostIPV6Address = inetAddress.getAddress();
                break;
            }
        }
    }
    // System.err.println("getThisHostIPV6Address: address is "
    // + Arrays.toString(thisHostIPV6Address));
    return thisHostIPV6Address;
}
 
Example 2
Source Project: brpc-java   File: DnsNamingService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> lookup(SubscribeInfo subscribeInfo) {
    InetAddress[] addresses;
    try {
        addresses = InetAddress.getAllByName(host);
    } catch (UnknownHostException ex) {
        throw new IllegalArgumentException("unknown http host");
    }

    List<ServiceInstance> instances = new ArrayList<ServiceInstance>();
    for (InetAddress address : addresses) {
        ServiceInstance instance = new ServiceInstance(address.getHostAddress(), port);
        if (subscribeInfo != null && StringUtils.isNoneBlank(subscribeInfo.getServiceId())) {
            instance.setServiceName(subscribeInfo.getServiceId());
        }
        instances.add(instance);
    }
    return instances;
}
 
Example 3
Source Project: zooadmin   File: BaseTool.java    License: MIT License 6 votes vote down vote up
public static String getServer() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ArrayList<String> endPoints = new ArrayList<String>();
    try {
        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);
        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);
            }
        }
    } catch (Exception e) {
        return "";
    }
    if (endPoints.size() > 0) {
        return endPoints.get(0);
    } else {
        return "";
    }
}
 
Example 4
private static byte[] getThisHostIPV6Address(String hostName)
        throws Exception {
    InetAddress[] thisHostIPAddresses = null;
    try {
        thisHostIPAddresses = InetAddress.getAllByName(InetAddress
                .getLocalHost().getHostName());
    } catch (UnknownHostException uhEx) {
        uhEx.printStackTrace();
        throw uhEx;
    }
    byte[] thisHostIPV6Address = null;
    for (InetAddress inetAddress : thisHostIPAddresses) {
        if (inetAddress instanceof Inet6Address) {
            if (inetAddress.getHostName().equals(hostName)) {
                thisHostIPV6Address = inetAddress.getAddress();
                break;
            }
        }
    }
    // System.err.println("getThisHostIPV6Address: address is "
    // + Arrays.toString(thisHostIPV6Address));
    return thisHostIPV6Address;
}
 
Example 5
Source Project: notSABS   File: ContentBlocker20.java    License: MIT License 6 votes vote down vote up
private Set<String> prepare() {
    List<String> urlsToCheck = getDenyUrl();
    Set<String> ipsToBlock = new HashSet<>();
    for (String url : urlsToCheck) {
        if (ipsToBlock.size() > 625) {
            break;
        }
        Log.i(LOG_TAG, "Checking url: " + url);
        try {
            InetAddress[] addresses = InetAddress.getAllByName(url);
            for (InetAddress inetAddress : addresses) {
                ipsToBlock.add(inetAddress.getHostAddress() + ":*;127.0.0.1:80");
                Log.i(LOG_TAG, "Address: " + inetAddress.getHostAddress());
            }
        } catch (UnknownHostException e) {
            Log.e(LOG_TAG, "Failed to resolve: " + url, e);
        }
    }
    return ipsToBlock;
}
 
Example 6
Source Project: RDFS   File: CPUParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads and parses /proc/cpuinfo and creates an appropriate 
 * EventRecord that holds the desirable information.
 * 
 * @param s unused parameter
 * 
 * @return the EventRecord created
 */
public EventRecord query(String s) throws Exception {
  StringBuffer sb = Environment.runCommand("cat /proc/cpuinfo");
  EventRecord retval = new EventRecord(InetAddress.getLocalHost()
      .getCanonicalHostName(), InetAddress.getAllByName(InetAddress.getLocalHost()
      .getHostName()), Calendar.getInstance(), "CPU", "Unknown", "CPU", "-");

  retval.set("processors", findAll("\\s*processor\\s*:\\s*(\\d+)", sb
      .toString(), 1, ", "));

  retval.set("model name", findPattern("\\s*model name\\s*:\\s*(.+)", sb
      .toString(), 1));

  retval.set("frequency", findAll("\\s*cpu\\s*MHz\\s*:\\s*(\\d+)", sb
      .toString(), 1, ", "));

  retval.set("physical id", findAll("\\s*physical\\s*id\\s*:\\s*(\\d+)", sb
      .toString(), 1, ", "));

  retval.set("core id", findAll("\\s*core\\s*id\\s*:\\s*(\\d+)", sb
      .toString(), 1, ", "));

  return retval;
}
 
Example 7
Source Project: big-c   File: TestDistributedShell.java    License: Apache License 2.0 6 votes vote down vote up
private boolean checkIPs(String hostname, String localIP, String appIP)
    throws Exception {

  if (localIP.equals(appIP)) {
    return true;
  }
  boolean appIPCheck = false;
  boolean localIPCheck = false;
  InetAddress[] addresses = InetAddress.getAllByName(hostname);
  for (InetAddress ia : addresses) {
    if (ia.getHostAddress().equals(appIP)) {
      appIPCheck = true;
      continue;
    }
    if (ia.getHostAddress().equals(localIP)) {
      localIPCheck = true;
    }
  }
  return (appIPCheck && localIPCheck);

}
 
Example 8
private Set<InetAddress> resolveDomainNames(String domainName) {
    Set<InetAddress> addresses = new HashSet<>();

    try {
        InetAddress[] inetAddresses;
        inetAddresses = InetAddress.getAllByName(domainName);

        addresses.addAll(
                Arrays.asList(inetAddresses)
        );

        logger.info(
                "Resolved domain name '" + domainName + "' to address(es): " + addresses
        );
    } catch (UnknownHostException e) {
        logger.severe(
                "Unable to resolve domain name " + domainName
        );
    }

    return addresses;
}
 
Example 9
Source Project: metron   File: MaasIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private boolean checkIPs(String hostname, String localIP, String appIP)
        throws Exception {

  if (localIP.equals(appIP)) {
    return true;
  }
  boolean appIPCheck = false;
  boolean localIPCheck = false;
  InetAddress[] addresses = InetAddress.getAllByName(hostname);
  for (InetAddress ia : addresses) {
    if (ia.getHostAddress().equals(appIP)) {
      appIPCheck = true;
      continue;
    }
    if (ia.getHostAddress().equals(localIP)) {
      localIPCheck = true;
    }
  }
  return (appIPCheck && localIPCheck);

}
 
Example 10
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);
    }
}
 
Example 11
/**
 * Returns all the IP addresses of the local host.
 */
public static HostAddresses getLocalAddresses() throws IOException
{
    String hostname = null;
    InetAddress[] inetAddresses = null;
    try {
        InetAddress localHost = InetAddress.getLocalHost();
        hostname = localHost.getHostName();
        inetAddresses = InetAddress.getAllByName(hostname);
        HostAddress[] hAddresses = new HostAddress[inetAddresses.length];
        for (int i = 0; i < inetAddresses.length; i++)
            {
                hAddresses[i] = new HostAddress(inetAddresses[i]);
            }
        if (DEBUG) {
            System.out.println(">>> KrbKdcReq local addresses for "
                               + hostname + " are: ");

            for (int i = 0; i < inetAddresses.length; i++) {
                System.out.println("\n\t" + inetAddresses[i]);
                if (inetAddresses[i] instanceof Inet4Address)
                    System.out.println("IPv4 address");
                if (inetAddresses[i] instanceof Inet6Address)
                    System.out.println("IPv6 address");
            }
        }
        return (new HostAddresses(hAddresses));
    } catch (Exception exc) {
        throw new IOException(exc.toString());
    }

}
 
Example 12
Source Project: hadoop-gpu   File: LogParser.java    License: Apache License 2.0 5 votes vote down vote up
protected void setNetworkProperties() {
  // determine hostname and ip addresses for the node
  try {
    // Get hostname
    hostname = InetAddress.getLocalHost().getCanonicalHostName();
    // Get all associated ip addresses
    ips = InetAddress.getAllByName(hostname);

  } catch (UnknownHostException e) {
    e.printStackTrace();
  }
}
 
Example 13
Source Project: apollo   File: DNSUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> resolve(String domainName) throws UnknownHostException {
  List<String> result = new ArrayList<>();

  InetAddress[] addresses = InetAddress.getAllByName(domainName);
  if (addresses != null) {
    for (InetAddress addr : addresses) {
      result.add(addr.getHostAddress());
    }
  }

  return result;
}
 
Example 14
/**
 * Resolve a host or IP address to an IP address.
 *
 * @return an {@link InetAddress}, or {@code null} if unable to be resolved (equivalent to
 *         {@code INADDR_ANY})
 */
static InetAddress resolveAddress(String ipOrHost) {
  if (!Strings.isNullOrEmpty(ipOrHost)) {
    if (InetAddresses.isInetAddress(ipOrHost)) {
      return InetAddresses.forString(ipOrHost);
    }
    try {
      InetAddress[] addresses = InetAddress.getAllByName(ipOrHost);
      return addresses[0];
    } catch (UnknownHostException ex) {
      logger.info("Unable to resolve '" + ipOrHost + "' to an address"); //$NON-NLS-1$ //$NON-NLS-2$
    }
  }
  return null;
}
 
Example 15
Source Project: j2objc   File: URLTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Android's URL.equals() works as if the network is down. This is different
 * from the RI, which does potentially slow and inconsistent DNS lookups in
 * URL.equals.
 */
public void testEqualsDoesNotDoHostnameResolution() throws Exception {
    for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
        String address = inetAddress.getHostAddress();
        if (inetAddress instanceof Inet6Address) {
            address = "[" + address + "]";
        }
        URL urlByHostName = new URL("http://localhost/foo?bar=baz#quux");
        URL urlByAddress = new URL("http://" + address + "/foo?bar=baz#quux");
        assertFalse("Expected " + urlByHostName + " to not equal " + urlByAddress,
                urlByHostName.equals(urlByAddress)); // fails on RI, which does DNS
    }
}
 
Example 16
Source Project: cordova-android-chromeview   File: Dns.java    License: Apache License 2.0 4 votes vote down vote up
@Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
  return InetAddress.getAllByName(host);
}
 
Example 17
Source Project: olat   File: WebDAVManagerImpl.java    License: Apache License 2.0 4 votes vote down vote up
private UserSession handleBasicAuthentication(final HttpServletRequest request, final HttpServletResponse response) {

        if (timedSessionCache == null) {
            synchronized (this) {
                timedSessionCache = coordinatorManager.getCoordinator().getCacher().getOrCreateCache(this.getClass(), "webdav");
            }
        }

        // Get the Authorization header, if one was supplied
        final String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            // fetch user session from a previous authentication
            UserSession usess = (UserSession) timedSessionCache.get(authHeader);
            if (usess != null && usess.isAuthenticated()) {
                return usess;
            }

            final StringTokenizer st = new StringTokenizer(authHeader);
            if (st.hasMoreTokens()) {
                final String basic = st.nextToken();

                // We only handle HTTP Basic authentication
                if (basic.equalsIgnoreCase("Basic")) {
                    final String credentials = st.nextToken();

                    // This example uses sun.misc.* classes.
                    // You will need to provide your own
                    // if you are not comfortable with that.
                    final String userPass = Base64Decoder.decode(credentials);

                    // The decoded string is in the form
                    // "userID:password".
                    final int p = userPass.indexOf(":");
                    if (p != -1) {
                        final String userID = userPass.substring(0, p);
                        final String password = userPass.substring(p + 1);

                        // Validate user ID and password
                        // and set valid true if valid.
                        // In this example, we simply check
                        // that neither field is blank
                        final Identity identity = WebDAVAuthManager.authenticate(userID, password);
                        if (identity != null) {
                            usess = UserSession.getUserSession(request);
                            usess.signOffAndClear();
                            usess.setIdentity(identity);
                            UserDeletionManager.getInstance().setIdentityAsActiv(identity);
                            // set the roles (admin, author, guest)
                            final Roles roles = baseSecurity.getRoles(identity);
                            usess.setRoles(roles);
                            // set authprovider
                            // usess.getIdentityEnvironment().setAuthProvider(OLATAuthenticationController.PROVIDER_OLAT);

                            // set session info
                            final SessionInfo sinfo = new SessionInfo(identity.getName(), request.getSession());
                            final User usr = identity.getUser();
                            sinfo.setFirstname(userService.getUserProperty(usr, UserConstants.FIRSTNAME));
                            sinfo.setLastname(userService.getUserProperty(usr, UserConstants.LASTNAME));
                            sinfo.setFromIP(request.getRemoteAddr());
                            sinfo.setFromFQN(request.getRemoteAddr());
                            try {
                                final InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr());
                                if (iaddr.length > 0) {
                                    sinfo.setFromFQN(iaddr[0].getHostName());
                                }
                            } catch (final UnknownHostException e) {
                                // ok, already set IP as FQDN
                            }
                            sinfo.setAuthProvider(AUTHENTICATION_PROVIDER_OLAT);
                            sinfo.setUserAgent(request.getHeader("User-Agent"));
                            sinfo.setSecure(request.isSecure());
                            sinfo.setWebDAV(true);
                            sinfo.setWebModeFromUreq(null);
                            // set session info for this session
                            usess.setSessionInfo(sinfo);
                            //
                            usess.signOn();
                            timedSessionCache.put(authHeader, usess);
                            return usess;
                        }
                    }
                }
            }
        }

        // If the user was not validated or the browser does not know about the realm yet, fail with a
        // 401 status code (UNAUTHORIZED) and
        // pass back a WWW-Authenticate header for
        // this servlet.
        //
        // Note that this is the normal situation the
        // first time you access the page. The client
        // web browser will prompt for userID and password
        // and cache them so that it doesn't have to
        // prompt you again.

        response.setHeader("WWW-Authenticate", "Basic realm=\"" + BASIC_AUTH_REALM + "\"");
        response.setStatus(401);
        return null;
    }
 
Example 18
Source Project: crate   File: NetworkService.java    License: Apache License 2.0 4 votes vote down vote up
/** resolves a single host specification */
private InetAddress[] resolveInternal(String host) throws IOException {
    if ((host.startsWith("#") && host.endsWith("#")) || (host.startsWith("_") && host.endsWith("_"))) {
        host = host.substring(1, host.length() - 1);
        // next check any registered custom resolvers if any
        if (customNameResolvers != null) {
            for (CustomNameResolver customNameResolver : customNameResolvers) {
                InetAddress[] addresses = customNameResolver.resolveIfPossible(host);
                if (addresses != null) {
                    return addresses;
                }
            }
        }
        switch (host) {
            case "local":
                return NetworkUtils.getLoopbackAddresses();
            case "local:ipv4":
                return NetworkUtils.filterIPV4(NetworkUtils.getLoopbackAddresses());
            case "local:ipv6":
                return NetworkUtils.filterIPV6(NetworkUtils.getLoopbackAddresses());
            case "site":
                return NetworkUtils.getSiteLocalAddresses();
            case "site:ipv4":
                return NetworkUtils.filterIPV4(NetworkUtils.getSiteLocalAddresses());
            case "site:ipv6":
                return NetworkUtils.filterIPV6(NetworkUtils.getSiteLocalAddresses());
            case "global":
                return NetworkUtils.getGlobalAddresses();
            case "global:ipv4":
                return NetworkUtils.filterIPV4(NetworkUtils.getGlobalAddresses());
            case "global:ipv6":
                return NetworkUtils.filterIPV6(NetworkUtils.getGlobalAddresses());
            default:
                /* an interface specification */
                if (host.endsWith(":ipv4")) {
                    host = host.substring(0, host.length() - 5);
                    return NetworkUtils.filterIPV4(NetworkUtils.getAddressesForInterface(host));
                } else if (host.endsWith(":ipv6")) {
                    host = host.substring(0, host.length() - 5);
                    return NetworkUtils.filterIPV6(NetworkUtils.getAddressesForInterface(host));
                } else {
                    return NetworkUtils.getAddressesForInterface(host);
                }
        }
    }
    return InetAddress.getAllByName(host);
}
 
Example 19
Source Project: reader   File: Dns.java    License: MIT License 4 votes vote down vote up
@Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
  return InetAddress.getAllByName(host);
}
 
Example 20
Source Project: HttpSessionReplacer   File: RedisConfiguration.java    License: MIT License 3 votes vote down vote up
/**
 * Resolves server DNS name if needed. Retrieves all IP addresses associated with DNS name.
 *
 * @param serverName
 *          DNS name or IP address
 * @return list of IP addresses associated with DNS name
 * @throws UnknownHostException
 *           if server name is not recognized by DNS
 */
private InetAddress[] resolveServers(String serverName) throws UnknownHostException {
  InetAddress[] hosts = InetAddress.getAllByName(serverName);
  if (logger.isInfoEnabled()) {
    logger.info("Resolved hosts from '{}', parsed={} resolved={}", server, serverName, Arrays.asList(hosts));
  }
  return hosts;
}