Java 类com.google.common.net.InetAddresses 实例源码

项目:hadoop-oss    文件:NuCypherExtClient.java   
/**
 * Return the socket addresses to use with each configured
 * local interface. Local interfaces may be specified by IP
 * address, IP address range using CIDR notation, interface
 * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
 * The socket addresses consist of the IPs for the interfaces
 * and the ephemeral port (port 0). If an IP, IP range, or
 * interface name matches an interface with sub-interfaces
 * only the IP of the interface is used. Sub-interfaces can
 * be used by specifying them explicitly (by IP or name).
 *
 * @return SocketAddresses for the configured local interfaces,
 *    or an empty array if none are configured
 * @throws UnknownHostException if a given interface name is invalid
 */
private static SocketAddress[] getLocalInterfaceAddrs(
    String interfaceNames[]) throws UnknownHostException {
  List<SocketAddress> localAddrs = new ArrayList<>();
  for (String interfaceName : interfaceNames) {
    if (InetAddresses.isInetAddress(interfaceName)) {
      localAddrs.add(new InetSocketAddress(interfaceName, 0));
    } else if (NetUtils.isValidSubnet(interfaceName)) {
      for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(addr, 0));
      }
    } else {
      for (String ip : DNS.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(ip, 0));
      }
    }
  }
  return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}
项目:open-rmbt    文件:Helperfunctions.java   
/**
 * Anonymize an IP address
 * @param inetAddress the IP address to be anonymized
 * @param replaceLastOctetWith the String which shall replace the last octet in IPv4
 * @return
 */
public static String anonymizeIp(final InetAddress inetAddress, String replaceLastOctetWith) {
    try
    {
        final byte[] address = inetAddress.getAddress();
        address[address.length - 1] = 0;
        if (address.length > 4) // ipv6
        {
            for (int i = 6; i < address.length; i++)
                address[i] = 0;
        }

        String result = InetAddresses.toAddrString(InetAddress.getByAddress(address));
        if (address.length == 4)
            result = result.replaceFirst(".0$", replaceLastOctetWith);
        return result;
    }
    catch (final Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
项目:creacoinj    文件:VersionMessage.java   
public VersionMessage(NetworkParameters params, int newBestHeight) {
    super(params);
    clientVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
    localServices = 0;
    time = System.currentTimeMillis() / 1000;
    // Note that the Bitcoin Core doesn't do anything with these, and finding out your own external IP address
    // is kind of tricky anyway, so we just put nonsense here for now.
    InetAddress localhost = InetAddresses.forString("127.0.0.1");
    myAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    theirAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    subVer = LIBRARY_SUBVER;
    bestHeight = newBestHeight;
    relayTxesBeforeFilter = true;

    length = 85;
    if (protocolVersion > 31402)
        length += 8;
    length += VarInt.sizeOf(subVer.length()) + subVer.length();
}
项目:Elasticsearch    文件:IpFieldMapper.java   
public static long ipToLong(String ip) {
    try {
        if (!InetAddresses.isInetAddress(ip)) {
            throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ip address");
        }
        String[] octets = pattern.split(ip);
        if (octets.length != 4) {
            throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ipv4 address (4 dots)");
        }
        return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
                (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
    } catch (Exception e) {
        if (e instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) e;
        }
        throw new IllegalArgumentException("failed to parse ip [" + ip + "]", e);
    }
}
项目:ios-device-control    文件:OpenUrlApp.java   
@Override
public CheckWifiResult checkWifi(IosDevice device) throws IosDeviceException {
  String output = runAppRobust(device, Duration.ofSeconds(15), "--check_wifi");
  Matcher ipMatcher = CHECK_WIFI_IP_ADDRESS_PATTERN.matcher(output);
  Matcher ssidMatcher = CHECK_WIFI_SSID_PATTERN.matcher(output);

  Optional<WifiConnection> connection;
  if (ipMatcher.find() && ssidMatcher.find()) {
    InetAddress ip = InetAddresses.forString(ipMatcher.group(1));
    String ssid = ssidMatcher.group(1);
    connection = Optional.of(new AutoValue_AppResult_WifiConnection(ip, ssid));
  } else {
    connection = Optional.empty();
  }

  return new CheckWifiResult(output, connection);
}
项目:hadoop    文件:DFSClient.java   
/**
 * Return the socket addresses to use with each configured
 * local interface. Local interfaces may be specified by IP
 * address, IP address range using CIDR notation, interface
 * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
 * The socket addresses consist of the IPs for the interfaces
 * and the ephemeral port (port 0). If an IP, IP range, or
 * interface name matches an interface with sub-interfaces
 * only the IP of the interface is used. Sub-interfaces can
 * be used by specifying them explicitly (by IP or name).
 * 
 * @return SocketAddresses for the configured local interfaces,
 *    or an empty array if none are configured
 * @throws UnknownHostException if a given interface name is invalid
 */
private static SocketAddress[] getLocalInterfaceAddrs(
    String interfaceNames[]) throws UnknownHostException {
  List<SocketAddress> localAddrs = new ArrayList<SocketAddress>();
  for (String interfaceName : interfaceNames) {
    if (InetAddresses.isInetAddress(interfaceName)) {
      localAddrs.add(new InetSocketAddress(interfaceName, 0));
    } else if (NetUtils.isValidSubnet(interfaceName)) {
      for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(addr, 0));
      }
    } else {
      for (String ip : DNS.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(ip, 0));
      }
    }
  }
  return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}
项目:redirector    文件:IpAddressValidator.java   
/**
 * Validates IP string, both IPV6 and IPV4
 * Also accounts for CIDR notation
 * Examples:
 * fe80::3ab1:dbff:fed1:c62d/64
 * 2001:db8::
 * 192.168.0.1
 * 2001:db8::/116
 * 192.168.0.0/32
 * ::/0
 *
 * @param address
 * @return
 */
public static boolean isValidIpString (String address) {
    int slashIndex = address.lastIndexOf('/');
    String ipAddressPart = address;
    Integer subnetPart;
    if (slashIndex != -1) {
        ipAddressPart = address.substring(0, slashIndex);
        try {
            subnetPart = Integer.parseInt(address.substring(slashIndex + 1, address.length()));
        } catch (NumberFormatException nfe) {
            return false;
        }
        if (subnetPart < 0) {
            return false;
        }
        if (subnetPart > 128) {
            return false;
        }
        if (subnetPart > 32 && ipAddressPart.contains(".")) {
            return false;
        }
    }
    return InetAddresses.isInetAddress(ipAddressPart);
}
项目:athena    文件:Ip6AddressTest.java   
/**
 * Tests valueOf() converter for IPv6 InetAddress.
 */
@Test
public void testValueOfInetAddressIPv6() {
    Ip6Address ipAddress;
    InetAddress inetAddress;

    inetAddress =
        InetAddresses.forString("1111:2222:3333:4444:5555:6666:7777:8888");
    ipAddress = Ip6Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(),
               is("1111:2222:3333:4444:5555:6666:7777:8888"));

    inetAddress = InetAddresses.forString("::");
    ipAddress = Ip6Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("::"));

    inetAddress =
        InetAddresses.forString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
    ipAddress = Ip6Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(),
               is("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
}
项目:athena    文件:IpAddressTest.java   
/**
 * Tests valueOf() converter for IPv4 InetAddress.
 */
@Test
public void testValueOfInetAddressIPv4() {
    IpAddress ipAddress;
    InetAddress inetAddress;

    inetAddress = InetAddresses.forString("1.2.3.4");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("1.2.3.4"));

    inetAddress = InetAddresses.forString("0.0.0.0");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("0.0.0.0"));

    inetAddress = InetAddresses.forString("255.255.255.255");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("255.255.255.255"));
}
项目:athena    文件:IpAddressTest.java   
/**
 * Tests valueOf() converter for IPv6 InetAddress.
 */
@Test
public void testValueOfInetAddressIPv6() {
    IpAddress ipAddress;
    InetAddress inetAddress;

    inetAddress =
        InetAddresses.forString("1111:2222:3333:4444:5555:6666:7777:8888");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(),
               is("1111:2222:3333:4444:5555:6666:7777:8888"));

    inetAddress = InetAddresses.forString("::");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("::"));

    inetAddress =
        InetAddresses.forString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
    ipAddress = IpAddress.valueOf(inetAddress);
    assertThat(ipAddress.toString(),
               is("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
}
项目:athena    文件:Ip4AddressTest.java   
/**
 * Tests valueOf() converter for IPv4 InetAddress.
 */
@Test
public void testValueOfInetAddressIPv4() {
    Ip4Address ipAddress;
    InetAddress inetAddress;

    inetAddress = InetAddresses.forString("1.2.3.4");
    ipAddress = Ip4Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("1.2.3.4"));

    inetAddress = InetAddresses.forString("0.0.0.0");
    ipAddress = Ip4Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("0.0.0.0"));

    inetAddress = InetAddresses.forString("255.255.255.255");
    ipAddress = Ip4Address.valueOf(inetAddress);
    assertThat(ipAddress.toString(), is("255.255.255.255"));
}
项目:athena    文件:FeatureDatabaseMgmtManager.java   
public String getValueFromrequestedObject(Object obj) {
    if (obj instanceof BigInteger) {
        return obj.toString();
    } else if (obj instanceof Integer) {
        return obj.toString();
    } else if (obj instanceof Long) {
        return obj.toString();

    } else if (obj instanceof Date) {
        Long tmp = ((Date) obj).getTime();
        return tmp.toString();

    } else if (obj instanceof InetAddress) {
        Integer addr = InetAddresses.coerceToInteger((InetAddress) obj);
        return addr.toString();
    } else {
        log.warn("input value has something problems");
        return null;
    }
}
项目:okwallet    文件:VersionMessage.java   
public VersionMessage(NetworkParameters params, int newBestHeight) {
    super(params);
    clientVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
    localServices = 0;
    time = System.currentTimeMillis() / 1000;
    // Note that the Bitcoin Core doesn't do anything with these, and finding out your own external IP address
    // is kind of tricky anyway, so we just put nonsense here for now.
    InetAddress localhost = InetAddresses.forString("127.0.0.1");
    myAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    theirAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
    subVer = LIBRARY_SUBVER;
    bestHeight = newBestHeight;
    relayTxesBeforeFilter = true;

    length = 85;
    if (protocolVersion > 31402)
        length += 8;
    length += VarInt.sizeOf(subVer.length()) + subVer.length();
}
项目:nomulus    文件:FullFieldsTestEntityHelper.java   
public static HostResource makeHostResource(
    String fqhn, @Nullable String ip1, @Nullable String ip2) {
  HostResource.Builder builder = new HostResource.Builder()
      .setRepoId(generateNewContactHostRoid())
      .setFullyQualifiedHostName(Idn.toASCII(fqhn))
      .setCreationTimeForTest(DateTime.parse("2000-10-08T00:45:00Z"))
      .setPersistedCurrentSponsorClientId("TheRegistrar");
  if ((ip1 != null) || (ip2 != null)) {
    ImmutableSet.Builder<InetAddress> ipBuilder = new ImmutableSet.Builder<>();
    if (ip1 != null) {
      ipBuilder.add(InetAddresses.forString(ip1));
    }
    if (ip2 != null) {
      ipBuilder.add(InetAddresses.forString(ip2));
    }
    builder.setInetAddresses(ipBuilder.build());
  }
  return builder.build();
}
项目:aliyun-oss-hadoop-fs    文件:DFSClient.java   
/**
 * Return the socket addresses to use with each configured
 * local interface. Local interfaces may be specified by IP
 * address, IP address range using CIDR notation, interface
 * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
 * The socket addresses consist of the IPs for the interfaces
 * and the ephemeral port (port 0). If an IP, IP range, or
 * interface name matches an interface with sub-interfaces
 * only the IP of the interface is used. Sub-interfaces can
 * be used by specifying them explicitly (by IP or name).
 *
 * @return SocketAddresses for the configured local interfaces,
 *    or an empty array if none are configured
 * @throws UnknownHostException if a given interface name is invalid
 */
private static SocketAddress[] getLocalInterfaceAddrs(
    String interfaceNames[]) throws UnknownHostException {
  List<SocketAddress> localAddrs = new ArrayList<>();
  for (String interfaceName : interfaceNames) {
    if (InetAddresses.isInetAddress(interfaceName)) {
      localAddrs.add(new InetSocketAddress(interfaceName, 0));
    } else if (NetUtils.isValidSubnet(interfaceName)) {
      for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(addr, 0));
      }
    } else {
      for (String ip : DNS.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(ip, 0));
      }
    }
  }
  return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}
项目:credhub    文件:CertificateGenerationParameters.java   
private GeneralNames buildAlternativeNames(CertificateGenerationRequestParameters params) {
  String[] alternativeNamesList = params.getAlternativeNames();
  if (alternativeNamesList == null){
    return null;
  }
  GeneralNamesBuilder builder = new GeneralNamesBuilder();

  for (String name :alternativeNamesList) {
    if (InetAddresses.isInetAddress(name)) {
      builder.addName(new GeneralName(GeneralName.iPAddress, name));
    } else  {
      builder.addName(new GeneralName(GeneralName.dNSName, name));
    }
  }
  return builder.build();
}
项目:PocketServer    文件:Packet.java   
protected static void writeAddress(ByteBuf buf, InetSocketAddress address) {
    Preconditions.checkArgument(!address.isUnresolved(), "address is not resolved");
    InetAddress addr = address.getAddress();

    if (addr.getClass() == Inet6Address.class) {
        Inet6Address temp = (Inet6Address) addr;
        try {
            addr = InetAddresses.getEmbeddedIPv4ClientAddress(temp);
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException("address type not supported", ex);
        }
    }

    buf.writeByte(0x04);
    for (byte b : addr.getAddress()) {
        buf.writeByte(~b & 0xFF);
    }
    buf.writeShort(address.getPort());
}
项目:Java-DB-IP    文件:JavaMapDbIpRepositoryImpl.java   
/**
 * Lookup GeoEntity for an InetAddress
 * @param inetAddress The InetAddress to be resolved.
 * @return A GeoEntity for an InetAddress
 */
@Override
public GeoEntity get(final InetAddress inetAddress) {
    PreConditions.checkNull(inetAddress, "inetAddress must not be null");
    GeoEntity result = null;
    if(inetAddress instanceof Inet4Address){
        final Integer startIpNum = InetAddresses.coerceToInteger(inetAddress);

        return IPV4_REPOSITORY.floorEntry(startIpNum) == null ? null
                : IPV4_REPOSITORY.floorEntry(startIpNum).getValue() ;
    }
    else{
        final BigInteger startIpBigInt = IPUtils.ipv6ToBigInteger(inetAddress);
        return IPV6_REPOSITORY.floorEntry(startIpBigInt) == null ? null
                : IPV6_REPOSITORY.floorEntry(startIpBigInt).getValue();

    }
}
项目:Java-DB-IP    文件:JavaMapDbIpRepositoryImpl.java   
/**
 * Save GeoEntity for an InetAddress
 * @param geoAttributes The attributes to be saved . Contains the attributes that will be needed 
 * as key and value to be put inside the TreeMap.
 */
@Override
public void save(final GeoAttributes geoAttributes) {
    PreConditions.checkNull(geoAttributes, "geoAttributes must not be null");
    final InetAddress startInetAddress = geoAttributes.getStartInetAddress();
    final InetAddress endInetAddress = geoAttributes.getEndInetAddress();
    final GeoEntity geoEntity = geoAttributes.getGeoEntity();

    if(startInetAddress instanceof Inet6Address
            && endInetAddress instanceof Inet6Address)
    {
        final BigInteger startIpBigInt = IPUtils.ipv6ToBigInteger(startInetAddress);
        IPV6_REPOSITORY.put(startIpBigInt,geoEntity);
    }
    else if (startInetAddress instanceof Inet4Address
            && endInetAddress instanceof Inet4Address)
    {
        final Integer startIpNum = InetAddresses.coerceToInteger(startInetAddress);
        IPV4_REPOSITORY.put(startIpNum,geoEntity);
    }
    else{
        //Well, this case should never happen. Maybe I'll throw in an exception later.
        logger.warn("This shouldn't ever happen");
    }
}
项目:big-c    文件:DFSClient.java   
/**
 * Return the socket addresses to use with each configured
 * local interface. Local interfaces may be specified by IP
 * address, IP address range using CIDR notation, interface
 * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
 * The socket addresses consist of the IPs for the interfaces
 * and the ephemeral port (port 0). If an IP, IP range, or
 * interface name matches an interface with sub-interfaces
 * only the IP of the interface is used. Sub-interfaces can
 * be used by specifying them explicitly (by IP or name).
 * 
 * @return SocketAddresses for the configured local interfaces,
 *    or an empty array if none are configured
 * @throws UnknownHostException if a given interface name is invalid
 */
private static SocketAddress[] getLocalInterfaceAddrs(
    String interfaceNames[]) throws UnknownHostException {
  List<SocketAddress> localAddrs = new ArrayList<SocketAddress>();
  for (String interfaceName : interfaceNames) {
    if (InetAddresses.isInetAddress(interfaceName)) {
      localAddrs.add(new InetSocketAddress(interfaceName, 0));
    } else if (NetUtils.isValidSubnet(interfaceName)) {
      for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(addr, 0));
      }
    } else {
      for (String ip : DNS.getIPs(interfaceName, false)) {
        localAddrs.add(new InetSocketAddress(ip, 0));
      }
    }
  }
  return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}
项目:graylog-plugin-pipeline-processor    文件:IpAddressConversion.java   
@Override
public IpAddress evaluate(FunctionArgs args, EvaluationContext context) {
    final String ipString = String.valueOf(ipParam.required(args, context));

    try {
        final InetAddress inetAddress = InetAddresses.forString(ipString);
        return new IpAddress(inetAddress);
    } catch (IllegalArgumentException e) {
        final Optional<String> defaultValue = defaultParam.optional(args, context);
        if (!defaultValue.isPresent()) {
            return new IpAddress(ANYV4);
        }
        try {
            return new IpAddress(InetAddresses.forString(defaultValue.get()));
        } catch (IllegalFormatException e1) {
            log.warn("Parameter `default` for to_ip() is not a valid IP address: {}", defaultValue.get());
            throw e1;
        }
    }
}
项目:netvirt    文件:OpenFlow13Provider.java   
public Flow createEgressClassifierTransportEgressRemoteFlow(NodeId nodeId, long nsp, long outport,
                                                            String firstHopIp) {
    MatchBuilder match = OpenFlow13Utils.getNspMatch(nsp);

    Long ipl = InetAddresses.coerceToInteger(InetAddresses.forString(firstHopIp)) & 0xffffffffL;
    List<Action> actionList = new ArrayList<>();
    actionList.add(OpenFlow13Utils.createActionNxLoadTunIpv4Dst(ipl, actionList.size()));
    actionList.add(OpenFlow13Utils.createActionOutPort("output:" + outport, actionList.size()));

    InstructionsBuilder isb = OpenFlow13Utils.wrapActionsIntoApplyActionsInstruction(actionList);
    String flowIdStr = EGRESS_CLASSIFIER_TPORTEGRESS_FLOW_NAME + nodeId.getValue() + "_" + nsp;

    return OpenFlow13Utils.createFlowBuilder(NwConstants.EGRESS_SFC_CLASSIFIER_EGRESS_TABLE,
        EGRESS_CLASSIFIER_EGRESS_REMOTE_PRIORITY, EGRESS_CLASSIFIER_TPORTEGRESS_COOKIE,
        EGRESS_CLASSIFIER_TPORTEGRESS_FLOW_NAME, flowIdStr, match, isb).build();
}
项目:netvirt    文件:Ipv6ServiceUtils.java   
public static Ipv6Address getIpv6SolicitedNodeMcastAddress(Ipv6Address ipv6Address) {

        /* According to RFC 4291, a Solicited Node Multicast Address is derived by adding the 24
           lower order bits with the Solicited Node multicast prefix (i.e., FF02::1:FF00:0/104).
           Example: For IPv6Address of FE80::2AA:FF:FE28:9C5A, the corresponding solicited node
           multicast address would be FF02::1:FF28:9C5A
         */

        byte[] octets;
        try {
            octets = InetAddress.getByName(ipv6Address.getValue()).getAddress();
        } catch (UnknownHostException e) {
            LOG.error("getIpv6SolicitedNodeMcastAddress: Failed to serialize ipv6Address ", e);
            return null;
        }

        // Return the address in its fully expanded format.
        Ipv6Address solictedV6Address = new Ipv6Address(InetAddresses.forString("ff02::1:ff"
                 + StringUtils.leftPad(Integer.toHexString(0xFF & octets[13]), 2, "0") + ":"
                 + StringUtils.leftPad(Integer.toHexString(0xFF & octets[14]), 2, "0")
                 + StringUtils.leftPad(Integer.toHexString(0xFF & octets[15]), 2, "0")).getHostAddress());

        return solictedV6Address;
    }
项目:SilverKing    文件:HostGroupTable.java   
private static void readLine(String line, HashedSetMap<String, InetAddress> hostGroupMap) {
    if (line != null) {
        line = line.trim();
        if (line.length() > 0) {
            String      ipToken;
            byte[]      ip;
            Set<String> hostGroups;
            String[]    tokens;

            tokens = line.split("\\s+");
            ipToken = tokens[0];
            hostGroups = new HashSet<String>();
            for (int i = 1; i < tokens.length; i++) {
                hostGroups.add(tokens[i]);
            }
            for (String hostGroup : hostGroups) {
                hostGroupMap.addValue(hostGroup, InetAddresses.forString(ipToken));
            }
        }
    }
}
项目:warp10-platform    文件:WorfInteractive.java   
private static String readHost(ConsoleReader reader, PrintWriter out, String prompt) {
  try {
    String inputString = readInputString(reader, out, prompt);

    if (InetAddresses.isInetAddress(inputString)) {
      return inputString;
    }
    out.println("Error, " + inputString + " is not a valid inet address");
  } catch (Exception exp) {
    if (WorfCLI.verbose) {
      exp.printStackTrace();
    }
    out.println("Error, unable to read the host. error=" + exp.getMessage());
  }
  return null;
}
项目:warp10-platform    文件:WorfInteractive.java   
private static String readInteger(ConsoleReader reader, PrintWriter out, String prompt) {
  try {
    String inputString = readInputString(reader, out, prompt);

    if (NumberUtils.isNumber(inputString)) {
      return inputString;
    }

    if (InetAddresses.isInetAddress(inputString)) {
      return inputString;
    }
    out.println("Error, " + inputString + " is not a number");
  } catch (Exception exp) {
    if (WorfCLI.verbose) {
      exp.printStackTrace();
    }
    out.println("Error, unable to read the host. error=" + exp.getMessage());
  }
  return null;
}
项目:Dream-Catcher    文件:DnsJavaResolver.java   
@Override
public Collection<InetAddress> resolveRemapped(String remappedHost) {
    // special case for IP literals: return the InetAddress without doing a dnsjava lookup. dnsjava seems to handle ipv4 literals
    // reasonably well, but does not handle ipv6 literals (with or without [] brackets) correctly.
    // note this does not work properly for ipv6 literals with a scope identifier, which is a known issue for InetAddresses.isInetAddress().
    // (dnsjava also handles the situation incorrectly)
    if (InetAddresses.isInetAddress(remappedHost)) {
        return Collections.singletonList(InetAddresses.forString(remappedHost));
    }

    // retrieve IPv4 addresses, then retrieve IPv6 addresses only if no IPv4 addresses are found. the current implementation always uses the
    // first returned address, so there is no need to look for IPv6 addresses if an IPv4 address is found.
    Collection<InetAddress> ipv4addresses = resolveHostByType(remappedHost, Type.A);

    if (!ipv4addresses.isEmpty()) {
        return ipv4addresses;
    } else {
        return resolveHostByType(remappedHost, Type.AAAA);
    }
}
项目:haven-platform    文件:DockerCluster.java   
private void rereadNode(SwarmNode sn) {
    String nodeName = getNodeName(sn);
    String address = getNodeAddress(sn);
    if(StringUtils.isEmpty(address)) {
        log.warn("Node {} does not contain address, it is usual for docker prior to 1.13 version.", nodeName);
        return;
    }
    try {
        if(InetAddresses.forString(sn.getStatus().getAddress()).isLoopbackAddress()) {
            //local node address it a wrong config, or user simply use single-node cluster - we can not detect
            // this, and just report it
            log.warn("Node {} report local address '{}', it may be wrong configuration.", nodeName, address);
        }
    } catch(Exception e) {
        log.warn("Node {} report wrong address '{}', it parsed with error:", nodeName, address, e);
    }
    NodeRegistration nr = updateNodeRegistration(nodeName, address, sn);
    if(!Objects.equals(getName(), nr.getCluster())) {
        log.info("Node {} is from another cluster: '{}', we remove it from our cluster: '{}'.", nodeName, nr.getCluster(), getName());
        leave(nodeName, sn);
    }
}
项目:nomulus    文件:CreateHostCommand.java   
@Override
protected void initMutatingEppToolCommand() {
  setSoyTemplate(HostCreateSoyInfo.getInstance(), HostCreateSoyInfo.HOSTCREATE);
  ImmutableList.Builder<String> ipv4Addresses = new ImmutableList.Builder<>();
  ImmutableList.Builder<String> ipv6Addresses = new ImmutableList.Builder<>();
  for (String address : nullToEmpty(addresses)) {
    InetAddress inetAddress = InetAddresses.forString(address);
    if (inetAddress instanceof Inet4Address) {
      ipv4Addresses.add(inetAddress.getHostAddress());
    } else if (inetAddress instanceof Inet6Address) {
      ipv6Addresses.add(inetAddress.getHostAddress());
    } else {
      throw new IllegalArgumentException(
          String.format("IP address in unknown format: %s", address));
    }
  }
  addSoyRecord(
      clientId,
      new SoyMapData(
          "hostname", hostName,
          "ipv4addresses", ipv4Addresses.build(),
          "ipv6addresses", ipv6Addresses.build()));
}
项目:nomulus    文件:NameserverWhoisResponseTest.java   
@Before
public void setUp() {
  persistNewRegistrar("example", "Example Registrar, Inc.", Registrar.Type.REAL, 8L);
  createTld("tld");

  hostResource1 = new HostResource.Builder()
      .setFullyQualifiedHostName("ns1.example.tld")
      .setPersistedCurrentSponsorClientId("example")
      .setInetAddresses(ImmutableSet.of(
          InetAddresses.forString("192.0.2.123"),
          InetAddresses.forString("2001:0DB8::1")))
      .setRepoId("1-EXAMPLE")
      .build();

  hostResource2 = new HostResource.Builder()
      .setFullyQualifiedHostName("ns2.example.tld")
      .setPersistedCurrentSponsorClientId("example")
      .setInetAddresses(ImmutableSet.of(
          InetAddresses.forString("192.0.2.123"),
          InetAddresses.forString("2001:0DB8::1")))
      .setRepoId("2-EXAMPLE")
      .build();
}
项目:nomulus    文件:DomainResourceToXjcConverterTest.java   
private static HostResource makeHostResource(
    FakeClock clock, String repoId, String fqhn, String ip) {
  clock.advanceOneMilli();
  return persistEppResource(
      new HostResource.Builder()
          .setCreationClientId("LawyerCat")
          .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
          .setPersistedCurrentSponsorClientId("BusinessCat")
          .setFullyQualifiedHostName(Idn.toASCII(fqhn))
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
          .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
          .setLastEppUpdateClientId("CeilingCat")
          .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
          .setRepoId(repoId)
          .setStatusValues(ImmutableSet.of(StatusValue.OK))
          .build());
}
项目:nomulus    文件:HostResourceToXjcConverterTest.java   
@Test
public void testConvertExternalHost_ipv6() throws Exception {
  XjcRdeHost bean = HostResourceToXjcConverter.convertExternalHost(
      new HostResource.Builder()
          .setCreationClientId("LawyerCat")
          .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
          .setPersistedCurrentSponsorClientId("BusinessCat")
          .setFullyQualifiedHostName("ns1.love.lol")
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba")))
          .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
          .setLastEppUpdateClientId("CeilingCat")
          .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
          .setRepoId("2-LOL")
          .setStatusValues(ImmutableSet.of(StatusValue.OK))
          .build());
  assertThat(bean.getAddrs()).hasSize(1);
  assertThat(bean.getAddrs().get(0).getIp().value()).isEqualTo("v6");
  assertThat(bean.getAddrs().get(0).getValue()).isEqualTo("cafe::abba");
}
项目:nomulus    文件:HostResourceToXjcConverterTest.java   
@Test
public void testHostStatusValueIsInvalid() throws Exception {
  assertThrows(
      IllegalArgumentException.class,
      () ->
          HostResourceToXjcConverter.convertExternalHost(
              new HostResource.Builder()
                  .setCreationClientId("LawyerCat")
                  .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
                  .setPersistedCurrentSponsorClientId("BusinessCat")
                  .setFullyQualifiedHostName("ns1.love.lol")
                  .setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba")))
                  .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
                  .setLastEppUpdateClientId("CeilingCat")
                  .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
                  .setRepoId("2-LOL")
                  .setStatusValues(ImmutableSet.of(StatusValue.SERVER_HOLD)) // <-- OOPS
                  .build()));
}
项目:nomulus    文件:HostResourceToXjcConverterTest.java   
@Test
public void testMarshal() throws Exception {
  // Bean! Bean! Bean!
  XjcRdeHostElement bean = HostResourceToXjcConverter.convertExternal(
      new HostResource.Builder()
          .setCreationClientId("LawyerCat")
          .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
          .setPersistedCurrentSponsorClientId("BusinessCat")
          .setFullyQualifiedHostName("ns1.love.lol")
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba")))
          .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
          .setLastEppUpdateClientId("CeilingCat")
          .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
          .setRepoId("2-LOL")
          .setStatusValues(ImmutableSet.of(StatusValue.OK))
          .build());
  marshalStrict(bean, new ByteArrayOutputStream(), UTF_8);
}
项目:nomulus    文件:RdeFixtures.java   
static HostResource makeHostResource(FakeClock clock, String fqhn, String ip) {
  clock.advanceOneMilli();
  return persistResourceWithCommitLog(
      new HostResource.Builder()
          .setRepoId(generateNewContactHostRoid())
          .setCreationClientId("LawyerCat")
          .setCreationTimeForTest(clock.nowUtc())
          .setPersistedCurrentSponsorClientId("BusinessCat")
          .setFullyQualifiedHostName(Idn.toASCII(fqhn))
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
          .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
          .setLastEppUpdateClientId("CeilingCat")
          .setLastEppUpdateTime(clock.nowUtc())
          .setStatusValues(ImmutableSet.of(StatusValue.OK))
          .build());
}
项目:nomulus    文件:XjcToHostResourceConverterTest.java   
@Test
public void testConvertHostResource() throws Exception {
  XjcRdeHost xjcHost = loadHostFromRdeXml();
  HostResource host = convertHostInTransaction(xjcHost);
  assertThat(host.getFullyQualifiedHostName()).isEqualTo("ns1.example1.test");
  assertThat(host.getRepoId()).isEqualTo("Hns1_example1_test-TEST");
  // The imported XML also had LINKED status, but that should have been dropped on import.
  assertThat(host.getStatusValues()).containsExactly(StatusValue.OK);
  assertThat(host.getInetAddresses())
      .containsExactly(
          InetAddresses.forString("192.0.2.2"),
          InetAddresses.forString("192.0.2.29"),
          InetAddresses.forString("1080:0:0:0:8:800:200C:417A"));
  assertThat(host.getPersistedCurrentSponsorClientId()).isEqualTo("RegistrarX");
  assertThat(host.getCreationClientId()).isEqualTo("RegistrarX");
  assertThat(host.getCreationTime()).isEqualTo(DateTime.parse("1999-05-08T12:10:00.0Z"));
  assertThat(host.getLastEppUpdateClientId()).isEqualTo("RegistrarX");
  assertThat(host.getLastEppUpdateTime()).isEqualTo(DateTime.parse("2009-10-03T09:34:00.0Z"));
  assertThat(host.getLastTransferTime()).isEqualTo(DateTime.parse("2008-10-03T09:34:00.0Z"));
}
项目:nomulus    文件:HostResourceTest.java   
@Test
public void testComputeLastTransferTime_hostCreatedAfterDomainWasTransferred() {
  // Domain was transferred on Day 1.
  // Host was created subordinate to domain on Day 2.
  domain = domain.asBuilder().setLastTransferTime(day1).build();
  host =
      persistResource(
          cloneAndSetAutoTimestamps(
              new HostResource.Builder()
                  .setCreationTime(day2)
                  .setRepoId("DEADBEEF-COM")
                  .setFullyQualifiedHostName("ns1.example.com")
                  .setCreationClientId("a registrar")
                  .setLastEppUpdateTime(clock.nowUtc())
                  .setLastEppUpdateClientId("another registrar")
                  .setInetAddresses(ImmutableSet.of(InetAddresses.forString("127.0.0.1")))
                  .setStatusValues(ImmutableSet.of(StatusValue.OK))
                  .setSuperordinateDomain(Key.create(domain))
                  .build()));
  assertThat(host.computeLastTransferTime(domain)).isNull();
}
项目:nomulus    文件:HostInfoFlowTest.java   
private HostResource persistHostResource() throws Exception {
  return persistResource(
      new HostResource.Builder()
          .setFullyQualifiedHostName(getUniqueIdFromCommand())
          .setRepoId("1FF-FOOBAR")
          .setPersistedCurrentSponsorClientId("my sponsor")
          .setStatusValues(ImmutableSet.of(StatusValue.CLIENT_UPDATE_PROHIBITED))
          .setInetAddresses(
              ImmutableSet.of(
                  InetAddresses.forString("192.0.2.2"),
                  InetAddresses.forString("1080:0:0:0:8:800:200C:417A"),
                  InetAddresses.forString("192.0.2.29")))
          .setPersistedCurrentSponsorClientId("TheRegistrar")
          .setCreationClientId("NewRegistrar")
          .setLastEppUpdateClientId("NewRegistrar")
          .setCreationTimeForTest(DateTime.parse("1999-04-03T22:00:00.0Z"))
          .setLastEppUpdateTime(DateTime.parse("1999-12-03T09:00:00.0Z"))
          .setLastTransferTime(DateTime.parse("2000-04-08T09:00:00.0Z"))
          .build());
}
项目:nomulus    文件:HostUpdateFlowTest.java   
@Test
public void testSuccess_authorizedClientReadFromSuperordinate() throws Exception {
  sessionMetadata.setClientId("NewRegistrar");
  createTld("tld");
  DomainResource domain =
      persistResource(
          newDomainResource("example.tld")
              .asBuilder()
              .setPersistedCurrentSponsorClientId("NewRegistrar")
              .build());
  persistResource(
      newHostResource("ns1.example.tld")
          .asBuilder()
          .setPersistedCurrentSponsorClientId("TheRegistrar") // Shouldn't hurt.
          .setSuperordinateDomain(Key.create(domain))
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString("127.0.0.1")))
          .build());

  clock.advanceOneMilli();
  runFlowAssertResponse(loadFile("host_update_response.xml"));
}