getAllByName ( )源码实例Demo

java.net.InetAddress#getAllByName ( )源码实例Demo

下面列出了java.net.InetAddress#getAllByName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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;
}
 
源代码2 项目: brpc-java   文件: DnsNamingService.java
@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;
}
 
源代码3 项目: zooadmin   文件: BaseTool.java
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 "";
    }
}
 
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;
}
 
源代码5 项目: notSABS   文件: ContentBlocker20.java
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;
}
 
源代码6 项目: RDFS   文件: CPUParser.java
/**
 * 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;
}
 
源代码7 项目: big-c   文件: TestDistributedShell.java
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);

}
 
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;
}
 
源代码9 项目: metron   文件: MaasIntegrationTest.java
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);

}
 
源代码10 项目: Cybernet-VPN   文件: OpenVPNService.java
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);
    }
}
 
源代码11 项目: openjdk-jdk8u-backup   文件: HostAddresses.java
/**
 * 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());
    }

}
 
源代码12 项目: hadoop-gpu   文件: LogParser.java
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();
  }
}
 
源代码13 项目: apollo   文件: DNSUtil.java
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;
}
 
/**
 * 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;
}
 
源代码15 项目: j2objc   文件: URLTest.java
/**
 * 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
    }
}
 
源代码16 项目: cordova-android-chromeview   文件: Dns.java
@Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
  return InetAddress.getAllByName(host);
}
 
源代码17 项目: olat   文件: WebDAVManagerImpl.java
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;
    }
 
源代码18 项目: crate   文件: NetworkService.java
/** 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);
}
 
源代码19 项目: reader   文件: Dns.java
@Override public InetAddress[] getAllByName(String host) throws UnknownHostException {
  return InetAddress.getAllByName(host);
}
 
源代码20 项目: HttpSessionReplacer   文件: RedisConfiguration.java
/**
 * 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;
}