com.google.common.net.InetAddresses Java Examples

The following examples show how to use com.google.common.net.InetAddresses. 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
Source File: IPAddresses.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * Get the IPv6 address for the host if any.
 *
 * @throws ConvergenceException if multiple addresses are found
 */
default Optional<Inet6Address> getIPv6Address(String hostname) {
    List<Inet6Address> ipv6addresses = Stream.of(getAddresses(hostname))
            .filter(Inet6Address.class::isInstance)
            .filter(inetAddress -> !inetAddress.isLoopbackAddress())
            .map(Inet6Address.class::cast)
            .filter(inetAddress -> !inetAddress.isLinkLocalAddress())
            .filter(inetAddress -> !inetAddress.isSiteLocalAddress())
            .collect(Collectors.toList());

    if (ipv6addresses.size() <= 1) return ipv6addresses.stream().findFirst();

    String addresses = ipv6addresses.stream().map(InetAddresses::toAddrString).collect(Collectors.joining(","));
    throw new ConvergenceException(
            String.format(
                    "Multiple IPv6 addresses found: %s. Perhaps a missing DNS entry or multiple AAAA records in DNS?",
                    addresses));
}
 
Example #2
Source File: DnsNameResolverTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveAll_nullResourceResolver() throws Exception {
  final String hostname = "addr.fake";
  final Inet4Address backendAddr = InetAddresses.fromInteger(0x7f000001);

  AddressResolver mockResolver = mock(AddressResolver.class);
  when(mockResolver.resolveAddress(Matchers.anyString()))
      .thenReturn(Collections.<InetAddress>singletonList(backendAddr));
  ResourceResolver resourceResolver = null;
  boolean resovleSrv = true;
  boolean resolveTxt = true;

  ResolutionResults res = DnsNameResolver.resolveAll(
      mockResolver, resourceResolver, resovleSrv, resolveTxt, hostname);
  assertThat(res.addresses).containsExactly(backendAddr);
  assertThat(res.balancerAddresses).isEmpty();
  assertThat(res.txtRecords).isEmpty();
  verify(mockResolver).resolveAddress(hostname);
}
 
Example #3
Source File: WorfInteractive.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: WorfInteractive.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: HostInfoFlowTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private HostResource persistHostResource() throws Exception {
  return persistResource(
      new HostResource.Builder()
          .setHostName(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());
}
 
Example #6
Source File: InterfaceAddress.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an InterfaceAddress from a String of the form 1.2.3.4/25.
 *
 * @throws IllegalArgumentException if the argument was duff.
 */
@Nonnull
public static InterfaceAddress forString(@Nonnull String addressString) {
    String netmaskString = null;
    int idx = addressString.indexOf('/');
    if (idx != -1) {
        netmaskString = addressString.substring(idx + 1);
        addressString = addressString.substring(0, idx);
    }
    InetAddress address = InetAddresses.forString(addressString);
    int netmask;
    if (netmaskString != null) {
        try {
            netmask = Integer.parseInt(netmaskString);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Cannot parse netmask from " + netmaskString, e);
        }
    } else {
        netmask = address.getAddress().length * Byte.SIZE;
    }
    return new InterfaceAddress(address, netmask);
}
 
Example #7
Source File: HostResourceToXjcConverterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertExternalHost_ipv6() {
  XjcRdeHost bean =
      HostResourceToXjcConverter.convertExternalHost(
          new HostResource.Builder()
              .setCreationClientId("LawyerCat")
              .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
              .setPersistedCurrentSponsorClientId("BusinessCat")
              .setHostName("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");
}
 
Example #8
Source File: DnsJavaResolver.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: HostResourceToXjcConverterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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")
              .setHostName("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);
}
 
Example #10
Source File: ExpectNetServicesReturnsAllServicesAsActive.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public void verify(final Node node) {
  final Map<String, Map<String, String>> result = node.execute(transaction);
  assertThat(result.keySet())
      .containsExactlyInAnyOrderElementsOf(Arrays.asList("p2p", "jsonrpc", "ws"));

  assertThat(InetAddresses.isUriInetAddress(result.get("p2p").get("host"))).isTrue();
  final int p2pPort = Integer.valueOf(result.get("p2p").get("port"));
  assertThat(NetworkUtility.isValidPort(p2pPort)).isTrue();

  assertThat(InetAddresses.isUriInetAddress(result.get("ws").get("host"))).isTrue();
  final int wsPort = Integer.valueOf(result.get("ws").get("port"));
  assertThat(NetworkUtility.isValidPort(wsPort)).isTrue();

  assertThat(InetAddresses.isUriInetAddress(result.get("jsonrpc").get("host"))).isTrue();
  final int jsonRpcPort = Integer.valueOf(result.get("jsonrpc").get("port"));
  assertThat(NetworkUtility.isValidPort(jsonRpcPort)).isTrue();
}
 
Example #11
Source File: RdeFixtures.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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")
          .setHostName(Idn.toASCII(fqhn))
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
          .setLastTransferTime(DateTime.parse("1990-01-01T00:00:00Z"))
          .setLastEppUpdateClientId("CeilingCat")
          .setLastEppUpdateTime(clock.nowUtc())
          .setStatusValues(ImmutableSet.of(StatusValue.OK))
          .build());
}
 
Example #12
Source File: InetAddressUtils.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
public static List<InetAddress> toInetAddressList(List<String> addressList) {
    if (CollectionUtils.isEmpty(addressList)) {
        return Collections.emptyList();
    }
    final List<InetAddress> inetAddressList = new ArrayList<InetAddress>(addressList.size());
    for (String ignoreAddress : addressList) {
        if (StringUtils.isBlank(ignoreAddress)) {
            continue;
        }
        // not throw UnknownHostException
        final InetAddress address = InetAddresses.forString(ignoreAddress);
        if (address != null) {
            inetAddressList.add(address);
        }
    }
    return inetAddressList;
}
 
Example #13
Source File: DnsJavaResolver.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: IpAddressTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #15
Source File: DomainBaseToXjcConverterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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")
          .setHostName(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());
}
 
Example #16
Source File: VersionMessage.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #17
Source File: DataManager.java    From RedisBungee with Eclipse Public License 1.0 6 votes vote down vote up
public InetAddress getIp(final UUID uuid) {
    ProxiedPlayer player = plugin.getProxy().getPlayer(uuid);

    if (player != null)
        return player.getAddress().getAddress();

    try {
        return ipCache.get(uuid, new Callable<InetAddress>() {
            @Override
            public InetAddress call() throws Exception {
                try (Jedis tmpRsc = plugin.getPool().getResource()) {
                    String result = tmpRsc.hget("player:" + uuid, "ip");
                    if (result == null)
                        throw new NullPointerException("user not found");
                    return InetAddresses.forString(result);
                }
            }
        });
    } catch (ExecutionException | UncheckedExecutionException e) {
        if (e.getCause() instanceof NullPointerException && e.getCause().getMessage().equals("user not found"))
            return null; // HACK
        plugin.getLogger().log(Level.SEVERE, "Unable to get IP", e);
        throw new RuntimeException("Unable to get IP for " + uuid, e);
    }
}
 
Example #18
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void resolve_serviceConfigMalformed_serviceConfigError() throws Exception {
  DnsNameResolver.enableTxt = true;
  InetAddress backendAddr = InetAddresses.fromInteger(0x7f000001);
  AddressResolver mockAddressResolver = mock(AddressResolver.class);
  when(mockAddressResolver.resolveAddress(anyString()))
      .thenReturn(Collections.singletonList(backendAddr));
  String name = "foo.googleapis.com";
  ResourceResolver mockResourceResolver = mock(ResourceResolver.class);
  when(mockResourceResolver.resolveTxt(anyString()))
      .thenReturn(Collections.singletonList("grpc_config=something invalid"));

  DnsNameResolver resolver = newResolver(name, 81);
  resolver.setAddressResolver(mockAddressResolver);
  resolver.setResourceResolver(mockResourceResolver);
  resolver.start(mockListener);
  assertEquals(1, fakeExecutor.runDueTasks());
  verify(mockListener).onResult(resultCaptor.capture());
  ResolutionResult result = resultCaptor.getValue();
  InetSocketAddress resolvedBackendAddr =
      (InetSocketAddress) Iterables.getOnlyElement(
          Iterables.getOnlyElement(result.getAddresses()).getAddresses());
  assertThat(resolvedBackendAddr.getAddress()).isEqualTo(backendAddr);
  verify(mockAddressResolver).resolveAddress(name);
  assertThat(result.getAttributes()).isEqualTo(Attributes.EMPTY);
  assertThat(result.getServiceConfig()).isNotNull();
  assertThat(result.getServiceConfig().getError()).isNotNull();
  verify(mockResourceResolver).resolveTxt(anyString());
}
 
Example #19
Source File: DockerOperationsImplTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyEtcHosts() {
    ContainerData containerData = mock(ContainerData.class);
    String hostname = "hostname";
    InetAddress ipV6Local = InetAddresses.forString("::1");
    InetAddress ipV4Local = InetAddresses.forString("127.0.0.1");

    dockerOperations.addEtcHosts(containerData, hostname, Optional.empty(), Optional.of(ipV6Local));

    verify(containerData, times(1)).addFile(
            fileSystem.getPath("/etc/hosts"),
            "# This file was generated by com.yahoo.vespa.hosted.node.admin.docker.DockerOperationsImpl\n" +
                    "127.0.0.1	localhost\n" +
                    "::1	localhost ip6-localhost ip6-loopback\n" +
                    "fe00::0	ip6-localnet\n" +
                    "ff00::0	ip6-mcastprefix\n" +
                    "ff02::1	ip6-allnodes\n" +
                    "ff02::2	ip6-allrouters\n" +
                    "0:0:0:0:0:0:0:1	hostname\n");

    dockerOperations.addEtcHosts(containerData, hostname, Optional.of(ipV4Local), Optional.of(ipV6Local));

    verify(containerData, times(1)).addFile(
            fileSystem.getPath("/etc/hosts"),
            "# This file was generated by com.yahoo.vespa.hosted.node.admin.docker.DockerOperationsImpl\n" +
                    "127.0.0.1	localhost\n" +
                    "::1	localhost ip6-localhost ip6-loopback\n" +
                    "fe00::0	ip6-localnet\n" +
                    "ff00::0	ip6-mcastprefix\n" +
                    "ff02::1	ip6-allnodes\n" +
                    "ff02::2	ip6-allrouters\n" +
                    "0:0:0:0:0:0:0:1	hostname\n" +
                    "127.0.0.1	hostname\n");
}
 
Example #20
Source File: TlsCredentials.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static InetAddress parseInetAddress(String asciiAddr) {
  try {
    return InetAddresses.forString(HostAndPort.fromString(asciiAddr).getHost());
  } catch (IllegalArgumentException e) {
    return null;
  }
}
 
Example #21
Source File: GrpcNameResolver.java    From saluki with Apache License 2.0 5 votes vote down vote up
private List<SocketAddress> IpResolved(List<EquivalentAddressGroup> servers,
    List<SocketAddress> addresses, String host, int port) {
  List<SocketAddress> hostAddressMapping = Lists.newArrayList();
  SocketAddress sock = new InetSocketAddress(InetAddresses.forString(host), port);
  hostAddressMapping.add(sock);
  addSocketAddress(servers, addresses, sock);
  return hostAddressMapping;
}
 
Example #22
Source File: NetworkSetTest.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
private static void addRange(@Nonnull NetworkSet set, @Nonnull String a, @Nonnull String b) {
    InetAddressRange range = new InetAddressRange(
            InetAddresses.forString(a),
            InetAddresses.forString(b));
    LOG.info("Add (inclusive) " + range);
    set.addRange(range);
}
 
Example #23
Source File: PortMapping.java    From helios with Apache License 2.0 5 votes vote down vote up
public PortMapping(@JsonProperty("ip") @Nullable final String ip,
                   @JsonProperty("internalPort") final int internalPort,
                   @JsonProperty("externalPort") @Nullable final Integer externalPort,
                   @JsonProperty("protocol") @Nullable final String protocol) {
  this.ip = ip;
  // Validate IP here instead of in PortMappingParser to guaruntee every instance has a valid IP
  if (ip != null && !InetAddresses.isInetAddress(this.ip)) {
    throw new IllegalArgumentException(ip + " is not a valid IP address.");
  }

  this.internalPort = internalPort;
  this.externalPort = externalPort;
  this.protocol = Optional.fromNullable(protocol).or(TCP);
}
 
Example #24
Source File: ShadedNettyGrpcServerFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
protected NettyServerBuilder newServerBuilder() {
    final String address = getAddress();
    final int port = getPort();
    if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
        return NettyServerBuilder.forPort(port);
    } else {
        return NettyServerBuilder.forAddress(new InetSocketAddress(InetAddresses.forString(address), port));
    }
}
 
Example #25
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher with MIT License 5 votes vote down vote up
/**
 * Converts a list of domain name Subject Alternative Names into ASN1Encodable GeneralNames objects, for use with
 * the Bouncy Castle certificate builder.
 *
 * @param subjectAlternativeNames domain name SANs to convert
 * @return a GeneralNames instance that includes the specifie dsubjectAlternativeNames as DNS name fields
 */
private static GeneralNames getDomainNameSANsAsASN1Encodable(List<String> subjectAlternativeNames) {
    List<GeneralName> encodedSANs = new ArrayList<>(subjectAlternativeNames.size());
    for (String subjectAlternativeName : subjectAlternativeNames) {
        // IP addresses use the IP Address tag instead of the DNS Name tag in the SAN list
        boolean isIpAddress = InetAddresses.isInetAddress(subjectAlternativeName);
        GeneralName generalName = new GeneralName(isIpAddress ? GeneralName.iPAddress : GeneralName.dNSName, subjectAlternativeName);
        encodedSANs.add(generalName);
    }

    return new GeneralNames(encodedSANs.toArray(new GeneralName[encodedSANs.size()]));
}
 
Example #26
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Converts a list of domain name Subject Alternative Names into ASN1Encodable GeneralNames objects, for use with
 * the Bouncy Castle certificate builder.
 *
 * @param subjectAlternativeNames domain name SANs to convert
 * @return a GeneralNames instance that includes the specifie dsubjectAlternativeNames as DNS name fields
 */
private static GeneralNames getDomainNameSANsAsASN1Encodable(List<String> subjectAlternativeNames) {
    List<GeneralName> encodedSANs = new ArrayList<>(subjectAlternativeNames.size());
    for (String subjectAlternativeName : subjectAlternativeNames) {
        // IP addresses use the IP Address tag instead of the DNS Name tag in the SAN list
        boolean isIpAddress = InetAddresses.isInetAddress(subjectAlternativeName);
        GeneralName generalName = new GeneralName(isIpAddress ? GeneralName.iPAddress : GeneralName.dNSName, subjectAlternativeName);
        encodedSANs.add(generalName);
    }

    return new GeneralNames(encodedSANs.toArray(new GeneralName[encodedSANs.size()]));
}
 
Example #27
Source File: ShadedNettyGrpcServerFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
@Override
protected NettyServerBuilder newServerBuilder() {
    final String address = getAddress();
    final int port = getPort();
    if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
        return NettyServerBuilder.forPort(port);
    } else {
        return NettyServerBuilder.forAddress(new InetSocketAddress(InetAddresses.forString(address), port));
    }
}
 
Example #28
Source File: AbstractDhcpReplyFactory.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
/** Utility: Sets the ServerIdentifier option in the reply. */
protected static void setServerIdentifier(
        @Nonnull DhcpMessage reply,
        @Nonnull InetAddress localAddress) {
    if (!AddressUtils.isZeroAddress(localAddress)) {
        reply.setServerHostname(InetAddresses.toAddrString(localAddress));
        reply.getOptions().add(new ServerIdentifier(localAddress));
    }
}
 
Example #29
Source File: HostResourceTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptySetsBecomeNull() {
  assertThat(new HostResource.Builder().setInetAddresses(null).build().inetAddresses).isNull();
  assertThat(new HostResource.Builder().setInetAddresses(ImmutableSet.of()).build().inetAddresses)
      .isNull();
  assertThat(
          new HostResource.Builder()
              .setInetAddresses(ImmutableSet.of(InetAddresses.forString("127.0.0.1")))
              .build()
              .inetAddresses)
      .isNotNull();
}
 
Example #30
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
/** Like {@link InetAddresses#toAddrString(InetAddress)} but accepts nulls. */
@CheckForNull
public static String toAddrString(@CheckForNull InetAddress address) {
    if (address == null)
        return null;
    return InetAddresses.toAddrString(address);
}