Пример #1
0
  public void testCompatIPv4Addresses() {
    String[] nonCompatAddresses = {
      "3ffe::1", "::", "::1",
    };

    for (int i = 0; i < nonCompatAddresses.length; i++) {
      InetAddress ip = InetAddresses.forString(nonCompatAddresses[i]);
      assertFalse(InetAddresses.isCompatIPv4Address((Inet6Address) ip));
      try {
        InetAddresses.getCompatIPv4Address((Inet6Address) ip);
        fail("IllegalArgumentException expected for '" + nonCompatAddresses[i] + "'");
      } catch (IllegalArgumentException expected) {
        // expected behavior
      }
    }

    String[] validCompatAddresses = {
      "::1.2.3.4", "::102:304",
    };
    String compatStr = "1.2.3.4";
    InetAddress compat = InetAddresses.forString(compatStr);

    for (int i = 0; i < validCompatAddresses.length; i++) {
      InetAddress ip = InetAddresses.forString(validCompatAddresses[i]);
      assertTrue("checking '" + validCompatAddresses[i] + "'", ip instanceof Inet6Address);
      assertTrue(
          "checking '" + validCompatAddresses[i] + "'",
          InetAddresses.isCompatIPv4Address((Inet6Address) ip));
      assertEquals(
          "checking '" + validCompatAddresses[i] + "'",
          compat,
          InetAddresses.getCompatIPv4Address((Inet6Address) ip));
    }
  }
Пример #2
0
 public void testTeredoAddress_nullServer() {
   InetAddresses.TeredoInfo info = new InetAddresses.TeredoInfo(null, null, 80, 1000);
   assertEquals(InetAddresses.forString("0.0.0.0"), info.getServer());
   assertEquals(InetAddresses.forString("0.0.0.0"), info.getClient());
   assertEquals(80, info.getPort());
   assertEquals(1000, info.getFlags());
 }
Пример #3
0
  public void testTeredoAddresses() {
    String[] nonTeredoAddresses = {
      "::1.2.3.4", "3ffe::1", "::", "::1",
    };

    for (int i = 0; i < nonTeredoAddresses.length; i++) {
      InetAddress ip = InetAddresses.forString(nonTeredoAddresses[i]);
      assertFalse(InetAddresses.isTeredoAddress((Inet6Address) ip));
      try {
        InetAddresses.getTeredoInfo((Inet6Address) ip);
        fail("IllegalArgumentException expected for '" + nonTeredoAddresses[i] + "'");
      } catch (IllegalArgumentException expected) {
        // expected behavior
      }
    }

    String validTeredoAddress = "2001:0000:4136:e378:8000:63bf:3fff:fdd2";
    String serverStr = "65.54.227.120";
    String clientStr = "192.0.2.45";
    int port = 40000;
    int flags = 0x8000;

    InetAddress ip = InetAddresses.forString(validTeredoAddress);
    assertTrue(InetAddresses.isTeredoAddress((Inet6Address) ip));
    InetAddresses.TeredoInfo teredo = InetAddresses.getTeredoInfo((Inet6Address) ip);

    InetAddress server = InetAddresses.forString(serverStr);
    assertEquals(server, teredo.getServer());

    InetAddress client = InetAddresses.forString(clientStr);
    assertEquals(client, teredo.getClient());

    assertEquals(port, teredo.getPort());
    assertEquals(flags, teredo.getFlags());
  }
Пример #4
0
  public void testGetEmbeddedIPv4ClientAddress() {
    Inet6Address testIp;

    // Test regular global unicast address.
    testIp = (Inet6Address) InetAddresses.forString("2001:db8::1");
    assertFalse(InetAddresses.hasEmbeddedIPv4ClientAddress(testIp));

    // Test ISATAP address.
    testIp = (Inet6Address) InetAddresses.forString("2001:db8::5efe:102:304");
    assertFalse(InetAddresses.hasEmbeddedIPv4ClientAddress(testIp));

    // Test compat address.
    testIp = (Inet6Address) InetAddresses.forString("::1.2.3.4");
    assertTrue(InetAddresses.hasEmbeddedIPv4ClientAddress(testIp));
    InetAddress ipv4 = InetAddresses.forString("1.2.3.4");
    assertEquals(ipv4, InetAddresses.getEmbeddedIPv4ClientAddress(testIp));

    // Test 6to4 address.
    testIp = (Inet6Address) InetAddresses.forString("2002:0102:0304::1");
    assertTrue(InetAddresses.hasEmbeddedIPv4ClientAddress(testIp));
    ipv4 = InetAddresses.forString("1.2.3.4");
    assertEquals(ipv4, InetAddresses.getEmbeddedIPv4ClientAddress(testIp));

    // Test Teredo address.
    testIp = (Inet6Address) InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd2");
    assertTrue(InetAddresses.hasEmbeddedIPv4ClientAddress(testIp));
    ipv4 = InetAddresses.forString("192.0.2.45");
    assertEquals(ipv4, InetAddresses.getEmbeddedIPv4ClientAddress(testIp));
  }
Пример #5
0
 public void testToUriStringIPv6() {
   // Unfortunately the InetAddress.toString() method for IPv6 addresses
   // does not collapse contiguous shorts of zeroes with the :: abbreviation.
   String ipStr = "3ffe::1";
   InetAddress ip = InetAddresses.forString(ipStr);
   assertEquals("[3ffe::1]", InetAddresses.toUriString(ip));
 }
  private boolean isValid() {
    if (myUseHTTPProxyRb.isSelected()) {
      String host = getText(myProxyHostTextField);
      if (host == null) {
        return false;
      }

      try {
        HostAndPort parsedHost = HostAndPort.fromString(host);
        if (parsedHost.hasPort()) {
          return false;
        }
        host = parsedHost.getHostText();

        try {
          InetAddresses.forString(host);
          return true;
        } catch (IllegalArgumentException e) {
          // it is not an IPv4 or IPv6 literal
        }

        InternetDomainName.from(host);
      } catch (IllegalArgumentException e) {
        return false;
      }

      if (myProxyAuthCheckBox.isSelected()) {
        return !StringUtil.isEmptyOrSpaces(myProxyLoginTextField.getText())
            && myProxyPasswordTextField.getPassword().length > 0;
      }
    }
    return true;
  }
  /**
   * Returns a {@code HostSpecifier} built from the provided {@code specifier}, which is already
   * known to be valid. If the {@code specifier} might be invalid, use {@link #from(String)}
   * instead.
   *
   * <p>The specifier must be in one of these formats:
   *
   * <ul>
   *   <li>A domain name, like {@code google.com}
   *   <li>A IPv4 address string, like {@code 127.0.0.1}
   *   <li>An IPv6 address string with or without brackets, like {@code [2001:db8::1]} or {@code
   *       2001:db8::1}
   * </ul>
   *
   * @throws IllegalArgumentException if the specifier is not valid.
   */
  public static HostSpecifier fromValid(String specifier) {
    // Verify that no port was specified, and strip optional brackets from
    // IPv6 literals.
    final HostAndPort parsedHost = HostAndPort.fromString(specifier);
    Preconditions.checkArgument(!parsedHost.hasPort());
    final String host = parsedHost.getHostText();

    // Try to interpret the specifier as an IP address.  Note we build
    // the address rather than using the .is* methods because we want to
    // use InetAddresses.toUriString to convert the result to a string in
    // canonical form.
    InetAddress addr = null;
    try {
      addr = InetAddresses.forString(host);
    } catch (IllegalArgumentException e) {
      // It is not an IPv4 or IPv6 literal
    }

    if (addr != null) {
      return new HostSpecifier(InetAddresses.toUriString(addr));
    }

    // It is not any kind of IP address; must be a domain name or invalid.

    // TODO(user): different versions of this for different factories?
    final InternetDomainName domain = InternetDomainName.from(host);

    if (domain.hasPublicSuffix()) {
      return new HostSpecifier(domain.name());
    }

    throw new IllegalArgumentException(
        "Domain name does not have a recognized public suffix: " + host);
  }
Пример #8
0
 public void testForStringIPv6Input() throws UnknownHostException {
   String ipStr = "3ffe::1";
   InetAddress ipv6Addr = null;
   // Shouldn't hit DNS, because it's an IP string literal.
   ipv6Addr = InetAddress.getByName(ipStr);
   assertEquals(ipv6Addr, InetAddresses.forString(ipStr));
   assertTrue(InetAddresses.isInetAddress(ipStr));
 }
Пример #9
0
 public void test3ff31() {
   try {
     InetAddresses.forString("3ffe:::1");
     fail("IllegalArgumentException expected");
   } catch (IllegalArgumentException expected) {
     // expected behavior
   }
   assertFalse(InetAddresses.isInetAddress("016.016.016.016"));
 }
Пример #10
0
 /**
  * Converts an IPv6 string literal (e.g., "1111:2222::8888") into an IP address.
  *
  * @param value an IPv6 address value in string form
  * @return an IPv6 address
  * @throws IllegalArgumentException if the argument is invalid
  */
 public static Ip6Address valueOf(String value) {
   InetAddress inetAddress = null;
   try {
     inetAddress = InetAddresses.forString(value);
   } catch (IllegalArgumentException e) {
     final String msg = "Invalid IP address string: " + value;
     throw new IllegalArgumentException(msg);
   }
   return valueOf(inetAddress);
 }
 @Override
 public boolean apply(String input) {
   try {
     // Note we can do this, as InetAddress is now on the white list
     return (InetAddresses.forString(input) instanceof Inet4Address);
   } catch (IllegalArgumentException e) {
     // could be a hostname
     return true;
   }
 }
Пример #12
0
 public InetAddress getInetAddress() {
   if (!fields.containsKey("gl2_remote_ip")) {
     return null;
   }
   final String ipAddr = (String) fields.get("gl2_remote_ip");
   try {
     return InetAddresses.forString(ipAddr);
   } catch (IllegalArgumentException ignored) {
     return null;
   }
 }
Пример #13
0
  public void testConvertDottedQuadToHex() throws UnknownHostException {
    String[] ipStrings = {
      "7::0.128.0.127", "7::0.128.0.128", "7::128.128.0.127", "7::0.128.128.127"
    };

    for (String ipString : ipStrings) {
      // Shouldn't hit DNS, because it's an IP string literal.
      InetAddress ipv6Addr = InetAddress.getByName(ipString);
      assertEquals(ipv6Addr, InetAddresses.forString(ipString));
      assertTrue(InetAddresses.isInetAddress(ipString));
    }
  }
  private String getConsumerEndpoint(String endpoint) {
    if (Strings.isNullOrEmpty(endpoint)) {
      Optional<InetAddress> address = getOneControlInetAddress();
      if (!address.isPresent()) {
        logger.warn("Could not determine MTOSI/OneControl consumer end point");
        return getEndPoint(InetAddresses.forString("127.0.0.1"));
      }
      return getEndPoint(address.get());
    }

    return endpoint;
  }
  @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;
      }
    }
  }
  private static InetAddress parseInetAddress(String addrStr) {
    if (addrStr == null || addrStr.isEmpty()) {
      return null;
    }

    try {
      return InetAddresses.forString(addrStr);
    } catch (IllegalArgumentException e) {
      log.error(String.format("Failed to parse Inet address string: %s", addrStr), e);
      return null;
    }
  }
Пример #17
0
  public void testForStringIPv6EightColons() throws UnknownHostException {
    String[] eightColons = {
      "::7:6:5:4:3:2:1", "::7:6:5:4:3:2:0", "7:6:5:4:3:2:1::", "0:6:5:4:3:2:1::",
    };

    for (int i = 0; i < eightColons.length; i++) {
      InetAddress ipv6Addr = null;
      // Shouldn't hit DNS, because it's an IP string literal.
      ipv6Addr = InetAddress.getByName(eightColons[i]);
      assertEquals(ipv6Addr, InetAddresses.forString(eightColons[i]));
      assertTrue(InetAddresses.isInetAddress(eightColons[i]));
    }
  }
Пример #18
0
  public void testMappedIPv4Addresses() throws UnknownHostException {
    /*
     * Verify that it is not possible to instantiate an Inet6Address
     * from an "IPv4 mapped" IPv6 address.  Our String-based method can
     * at least identify them, however.
     */
    String mappedStr = "::ffff:192.168.0.1";
    assertTrue(InetAddresses.isMappedIPv4Address(mappedStr));
    InetAddress mapped = InetAddresses.forString(mappedStr);
    assertThat(mapped).isNotInstanceOf(Inet6Address.class);
    assertEquals(InetAddress.getByName("192.168.0.1"), mapped);

    // check upper case
    mappedStr = "::FFFF:192.168.0.1";
    assertTrue(InetAddresses.isMappedIPv4Address(mappedStr));
    mapped = InetAddresses.forString(mappedStr);
    assertThat(mapped).isNotInstanceOf(Inet6Address.class);
    assertEquals(InetAddress.getByName("192.168.0.1"), mapped);

    mappedStr = "0:00:000:0000:0:ffff:1.2.3.4";
    assertTrue(InetAddresses.isMappedIPv4Address(mappedStr));
    mapped = InetAddresses.forString(mappedStr);
    assertThat(mapped).isNotInstanceOf(Inet6Address.class);
    assertEquals(InetAddress.getByName("1.2.3.4"), mapped);

    mappedStr = "::ffff:0102:0304";
    assertTrue(InetAddresses.isMappedIPv4Address(mappedStr));
    mapped = InetAddresses.forString(mappedStr);
    assertThat(mapped).isNotInstanceOf(Inet6Address.class);
    assertEquals(InetAddress.getByName("1.2.3.4"), mapped);

    assertFalse(InetAddresses.isMappedIPv4Address("::"));
    assertFalse(InetAddresses.isMappedIPv4Address("::ffff"));
    assertFalse(InetAddresses.isMappedIPv4Address("::ffff:0"));
    assertFalse(InetAddresses.isMappedIPv4Address("::fffe:0:0"));
    assertFalse(InetAddresses.isMappedIPv4Address("::1:ffff:0:0"));
    assertFalse(InetAddresses.isMappedIPv4Address("foo"));
    assertFalse(InetAddresses.isMappedIPv4Address("192.0.2.1"));
  }
Пример #19
0
  public void testIsatapAddresses() {
    InetAddress ipv4 = InetAddresses.forString("1.2.3.4");
    String[] validIsatapAddresses = {
      "2001:db8::5efe:102:304",
      "2001:db8::100:5efe:102:304", // Private Multicast? Not likely.
      "2001:db8::200:5efe:102:304",
      "2001:db8::300:5efe:102:304" // Public Multicast? Also unlikely.
    };
    String[] nonIsatapAddresses = {
      "::1.2.3.4",
      "3ffe::1",
      "::",
      "::1",
      "2001:db8::0040:5efe:102:304",
      "2001:db8::5ffe:102:304",
      "2001:db8::5eff:102:304",
      "2001:0:102:203:200:5efe:506:708", // Teredo address; not ISATAP
    };

    for (int i = 0; i < validIsatapAddresses.length; i++) {
      InetAddress ip = InetAddresses.forString(validIsatapAddresses[i]);
      assertTrue(InetAddresses.isIsatapAddress((Inet6Address) ip));
      assertEquals(
          "checking '" + validIsatapAddresses[i] + "'",
          ipv4,
          InetAddresses.getIsatapIPv4Address((Inet6Address) ip));
    }
    for (int i = 0; i < nonIsatapAddresses.length; i++) {
      InetAddress ip = InetAddresses.forString(nonIsatapAddresses[i]);
      assertFalse(InetAddresses.isIsatapAddress((Inet6Address) ip));
      try {
        InetAddresses.getIsatapIPv4Address((Inet6Address) ip);
        fail("IllegalArgumentException expected for '" + nonIsatapAddresses[i] + "'");
      } catch (IllegalArgumentException expected) {
        // expected behavior
      }
    }
  }
public class IpAddressConversion extends AbstractFunction<IpAddress> {

  public static final String NAME = "to_ip";
  private static final InetAddress ANYV4 = InetAddresses.forString("0.0.0.0");

  private final ParameterDescriptor<Object, Object> ipParam;
  private final ParameterDescriptor<String, String> defaultParam;

  public IpAddressConversion() {
    ipParam = ParameterDescriptor.object("ip").description("Value to convert").build();
    defaultParam =
        ParameterDescriptor.string("default")
            .optional()
            .description("Used when 'ip' is null or malformed, defaults to '0.0.0.0'")
            .build();
  }

  @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;
      }
    }
  }

  @Override
  public FunctionDescriptor<IpAddress> descriptor() {
    return FunctionDescriptor.<IpAddress>builder()
        .name(NAME)
        .returnType(IpAddress.class)
        .params(of(ipParam, defaultParam))
        .description("Converts a value to an IPAddress using its string representation")
        .build();
  }
}
Пример #21
0
  public void test6to4Addresses() {
    String[] non6to4Addresses = {
      "::1.2.3.4", "3ffe::1", "::", "::1",
    };

    for (int i = 0; i < non6to4Addresses.length; i++) {
      InetAddress ip = InetAddresses.forString(non6to4Addresses[i]);
      assertFalse(InetAddresses.is6to4Address((Inet6Address) ip));
      try {
        InetAddresses.get6to4IPv4Address((Inet6Address) ip);
        fail("IllegalArgumentException expected for '" + non6to4Addresses[i] + "'");
      } catch (IllegalArgumentException expected) {
        // expected behavior
      }
    }

    String valid6to4Address = "2002:0102:0304::1";
    String ipv4Str = "1.2.3.4";

    InetAddress ipv4 = InetAddresses.forString(ipv4Str);
    InetAddress ip = InetAddresses.forString(valid6to4Address);
    assertTrue(InetAddresses.is6to4Address((Inet6Address) ip));
    assertEquals(ipv4, InetAddresses.get6to4IPv4Address((Inet6Address) ip));
  }
Пример #22
0
  @Override
  public Session toManagementSession() {
    SessionBuilder builder = new SessionBuilder();

    builder.setSessionId(getSessionId());
    IpAddress address;
    InetAddress address1 = InetAddresses.forString(header.getAddress());
    if (address1 instanceof Inet4Address) {
      address = new IpAddress(new Ipv4Address(header.getAddress()));
    } else {
      address = new IpAddress(new Ipv6Address(header.getAddress()));
    }
    builder.setSourceHost(new Host(address));

    Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1);
    String formattedDateTime = dateFormatter.format(loginTime);

    Matcher matcher = dateTimePattern.matcher(formattedDateTime);
    Preconditions.checkState(
        matcher.matches(),
        "Formatted datetime %s does not match pattern %s",
        formattedDateTime,
        dateTimePattern);
    builder.setLoginTime(new DateAndTime(formattedDateTime));

    builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail));
    builder.setInRpcs(new ZeroBasedCounter32(inRpcSuccess));
    builder.setOutRpcErrors(new ZeroBasedCounter32(outRpcError));

    builder.setUsername(header.getUserName());
    builder.setTransport(getTransportForString(header.getTransport()));

    builder.setOutNotifications(new ZeroBasedCounter32(outNotification));

    builder.setKey(new SessionKey(getSessionId()));

    Session1Builder builder1 = new Session1Builder();
    builder1.setSessionIdentifier(header.getSessionIdentifier());
    builder.addAugmentation(Session1.class, builder1.build());

    return builder.build();
  }
Пример #23
0
 public void testForUriStringIPv6() {
   Inet6Address expected = (Inet6Address) InetAddresses.forString("3ffe:0:0:0:0:0:0:1");
   assertEquals(expected, InetAddresses.forUriString("[3ffe:0:0:0:0:0:0:1]"));
 }
public final class TcpStreamSocketConnectionTest {
  private static final int LISTEN_PORT = 1234;
  private static final InetSocketAddress address =
      new InetSocketAddress(InetAddresses.forString("127.0.0.1"), LISTEN_PORT);

  @Before
  public void setUp() throws Exception {
    ByteBufPool.clear();
    ByteBufPool.setSizes(0, Integer.MAX_VALUE);
  }

  @Test
  public void test() throws Exception {
    final List<Integer> source = Lists.newArrayList();
    for (int i = 0; i < 5; i++) {
      source.add(i);
    }

    final NioEventloop eventloop = new NioEventloop();

    final StreamConsumers.ToList<Integer> consumerToList = StreamConsumers.toList(eventloop);

    SimpleNioServer server =
        new SimpleNioServer(eventloop) {
          @Override
          protected SocketConnection createConnection(SocketChannel socketChannel) {
            return new TcpStreamSocketConnection(eventloop, socketChannel) {
              @Override
              protected void wire(
                  StreamProducer<ByteBuf> socketReader, StreamConsumer<ByteBuf> socketWriter) {
                StreamBinaryDeserializer<Integer> streamDeserializer =
                    new StreamBinaryDeserializer<>(eventloop, intSerializer(), 10);
                streamDeserializer.streamTo(consumerToList);
                socketReader.streamTo(streamDeserializer);
              }
            };
          }
        };
    server.setListenAddress(address).acceptOnce();
    server.listen();

    final StreamBinarySerializer<Integer> streamSerializer =
        new StreamBinarySerializer<>(eventloop, intSerializer(), 1, 10, 0, false);
    reconnect(
        eventloop,
        address,
        defaultSocketSettings(),
        3,
        100L,
        new ConnectCallback() {
          @Override
          public void onConnect(SocketChannel socketChannel) {
            SocketConnection connection =
                new TcpStreamSocketConnection(eventloop, socketChannel) {
                  @Override
                  protected void wire(
                      StreamProducer<ByteBuf> socketReader, StreamConsumer<ByteBuf> socketWriter) {
                    streamSerializer.streamTo(socketWriter);
                    StreamProducers.ofIterable(eventloop, source).streamTo(streamSerializer);
                  }
                };
            connection.register();
          }

          @Override
          public void onException(Exception exception) {
            fail();
          }
        });

    eventloop.run();

    assertEquals(source, consumerToList.getList());

    assertEquals(getPoolItemsString(), ByteBufPool.getCreatedItems(), ByteBufPool.getPoolItems());
  }

  @Test
  public void testLoopback() throws Exception {
    final List<Integer> source = Lists.newArrayList();
    for (int i = 0; i < 1; i++) {
      source.add(i);
    }

    final NioEventloop eventloop = new NioEventloop();

    final StreamConsumers.ToList<Integer> consumerToList = StreamConsumers.toList(eventloop);

    SimpleNioServer server =
        new SimpleNioServer(eventloop) {
          @Override
          protected SocketConnection createConnection(SocketChannel socketChannel) {
            return new TcpStreamSocketConnection(eventloop, socketChannel) {
              @Override
              protected void wire(
                  StreamProducer<ByteBuf> socketReader, StreamConsumer<ByteBuf> socketWriter) {
                socketReader.streamTo(socketWriter);
              }
            };
          }
        };
    server.setListenAddress(address).acceptOnce();
    server.listen();

    final StreamBinarySerializer<Integer> streamSerializer =
        new StreamBinarySerializer<>(eventloop, intSerializer(), 1, 10, 0, false);
    final StreamBinaryDeserializer<Integer> streamDeserializer =
        new StreamBinaryDeserializer<>(eventloop, intSerializer(), 10);
    reconnect(
        eventloop,
        address,
        defaultSocketSettings(),
        3,
        100L,
        new ConnectCallback() {
          @Override
          public void onConnect(SocketChannel socketChannel) {
            SocketConnection connection =
                new TcpStreamSocketConnection(eventloop, socketChannel) {
                  @Override
                  protected void wire(
                      StreamProducer<ByteBuf> socketReader, StreamConsumer<ByteBuf> socketWriter) {
                    streamSerializer.streamTo(socketWriter);
                    socketReader.streamTo(streamDeserializer);
                  }
                };
            connection.register();
            StreamProducers.ofIterable(eventloop, source).streamTo(streamSerializer);
            streamDeserializer.streamTo(consumerToList);
          }

          @Override
          public void onException(Exception exception) {
            fail();
          }
        });

    eventloop.run();

    assertEquals(source, consumerToList.getList());

    assertEquals(getPoolItemsString(), ByteBufPool.getCreatedItems(), ByteBufPool.getPoolItems());
  }
}
Пример #25
0
 public void testForUriStringIPv4Mapped() {
   Inet4Address expected = (Inet4Address) InetAddresses.forString("192.0.2.1");
   assertEquals(expected, InetAddresses.forUriString("[::ffff:192.0.2.1]"));
 }
Пример #26
0
 public static PeerAddress localhost(NetworkParameters params) {
   return new PeerAddress(InetAddresses.forString("127.0.0.1"), params.getPort());
 }
Пример #27
0
 public void testFromInteger() {
   assertEquals(InetAddresses.fromInteger(0x7f000001), InetAddresses.forString("127.0.0.1"));
 }
Пример #28
0
 public void testToInteger() {
   InetAddress ipv4Addr = InetAddresses.forString("127.0.0.1");
   assertEquals(0x7f000001, InetAddresses.coerceToInteger(ipv4Addr));
 }
Пример #29
0
  public void testGetCoercedIPv4Address() {
    // Check that a coerced IPv4 address is unaltered.
    InetAddress localHost4 = InetAddresses.forString("127.0.0.1");
    assertEquals(localHost4, InetAddresses.getCoercedIPv4Address(localHost4));

    // ::1 special case
    assertEquals(localHost4, InetAddresses.getCoercedIPv4Address(InetAddresses.forString("::1")));

    // :: special case
    assertEquals(
        InetAddresses.forString("0.0.0.0"),
        InetAddresses.getCoercedIPv4Address(InetAddresses.forString("::")));

    // test compat address (should be hashed)
    assertTrue(
        InetAddresses.forString("1.2.3.4")
            != InetAddresses.getCoercedIPv4Address(InetAddresses.forString("::1.2.3.4")));

    // test 6to4 address (should be hashed)
    assertTrue(
        InetAddresses.forString("1.2.3.4")
            != InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2002:0102:0304::1")));

    // 2 6to4 addresses differing in the embedded IPv4 address should
    // hash to the different values.
    assertTrue(
        InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2002:0102:0304::1"))
            != InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2002:0506:0708::1")));

    // 2 6to4 addresses NOT differing in the embedded IPv4 address should
    // hash to the same value.
    assertTrue(
        InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2002:0102:0304::1"))
            != InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2002:0102:0304::2")));

    // test Teredo address (should be hashed)
    assertTrue(
        InetAddresses.forString("192.0.2.45")
            != InetAddresses.getCoercedIPv4Address(
                InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd2")));

    // 2 Teredo addresses differing in the embedded IPv4 address should
    // hash to the different values.
    assertTrue(
        InetAddresses.getCoercedIPv4Address(
                InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd2"))
            != InetAddresses.getCoercedIPv4Address(
                InetAddresses.forString("2001:0000:4136:e379:8000:63bf:3fff:fdd2")));

    // 2 Teredo addresses NOT differing in the embedded IPv4 address should
    // hash to the same value.
    assertEquals(
        InetAddresses.getCoercedIPv4Address(
            InetAddresses.forString("2001:0000:4136:e378:8000:63bf:3fff:fdd2")),
        InetAddresses.getCoercedIPv4Address(
            InetAddresses.forString("2001:0000:4136:e378:9000:63bf:3fff:fdd2")));

    // Test that an address hashes in to the 224.0.0.0/3 number-space.
    InetAddress coerced =
        InetAddresses.getCoercedIPv4Address(InetAddresses.forString("2001:4860::1"));
    assertTrue(0xe0000000 <= InetAddresses.coerceToInteger(coerced));
    assertTrue(InetAddresses.coerceToInteger(coerced) <= 0xfffffffe);
  }
Пример #30
0
  public void testForStringBogusInput() {
    String[] bogusInputs = {
      "",
      "016.016.016.016",
      "016.016.016",
      "016.016",
      "016",
      "000.000.000.000",
      "000",
      "0x0a.0x0a.0x0a.0x0a",
      "0x0a.0x0a.0x0a",
      "0x0a.0x0a",
      "0x0a",
      "42.42.42.42.42",
      "42.42.42",
      "42.42",
      "42",
      "42..42.42",
      "42..42.42.42",
      "42.42.42.42.",
      "42.42.42.42...",
      ".42.42.42.42",
      "...42.42.42.42",
      "42.42.42.-0",
      "42.42.42.+0",
      ".",
      "...",
      "bogus",
      "bogus.com",
      "192.168.0.1.com",
      "12345.67899.-54321.-98765",
      "257.0.0.0",
      "42.42.42.-42",
      "3ffe::1.net",
      "3ffe::1::1",
      "1::2::3::4:5",
      "::7:6:5:4:3:2:", // should end with ":0"
      ":6:5:4:3:2:1::", // should begin with "0:"
      "2001::db:::1",
      "FEDC:9878",
      "+1.+2.+3.4",
      "1.2.3.4e0",
      "::7:6:5:4:3:2:1:0", // too many parts
      "7:6:5:4:3:2:1:0::", // too many parts
      "9:8:7:6:5:4:3::2:1", // too many parts
      "0:1:2:3::4:5:6:7", // :: must remove at least one 0.
      "3ffe:0:0:0:0:0:0:0:1", // too many parts (9 instead of 8)
      "3ffe::10000", // hextet exceeds 16 bits
      "3ffe::goog",
      "3ffe::-0",
      "3ffe::+0",
      "3ffe::-1",
      ":",
      ":::",
      "::1.2.3",
      "::1.2.3.4.5",
      "::1.2.3.4:",
      "1.2.3.4::",
      "2001:db8::1:",
      ":2001:db8::1",
      ":1:2:3:4:5:6:7",
      "1:2:3:4:5:6:7:",
      ":1:2:3:4:5:6:"
    };

    for (int i = 0; i < bogusInputs.length; i++) {
      try {
        InetAddresses.forString(bogusInputs[i]);
        fail("IllegalArgumentException expected for '" + bogusInputs[i] + "'");
      } catch (IllegalArgumentException expected) {
        // expected behavior
      }
      assertFalse(InetAddresses.isInetAddress(bogusInputs[i]));
    }
  }