Java 类io.netty.util.NetUtil 实例源码

项目:netty-socks    文件:SSocksConnectHandler.java   
private ByteBuf getEncodedTargetAddress(ByteBufAllocator allocator, boolean resolve) throws ProxyConnectException {
    InetSocketAddress remoteAddress = destinationAddress();
    SocksAddressType remoteAddressType;
    String remoteHost;
    if (!resolve || remoteAddress.isUnresolved()) {
        remoteAddressType = SocksAddressType.DOMAIN;
        remoteHost = remoteAddress.getHostString();
    } else {
        remoteHost = remoteAddress.getAddress().getHostAddress();
        if (NetUtil.isValidIpV4Address(remoteHost)) {
            remoteAddressType = SocksAddressType.IPv4;
        } else if (NetUtil.isValidIpV6Address(remoteHost)) {
            remoteAddressType = SocksAddressType.IPv6;
        } else {
            throw new ProxyConnectException("unknown address type: " + StringUtil.simpleClassName(remoteHost));
        }
    }
    int remotePort = remoteAddress.getPort();
    SocksCmdRequest request = new SocksCmdRequest(SocksCmdType.UNKNOWN, remoteAddressType, remoteHost, remotePort);
    return SSocksAddressEncoder.INSTANCE.encode(allocator, request);
}
项目:moonlight-ss    文件:ShadowSocksRequest.java   
public byte[] encodeToBytes() throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byteArrayOutputStream.write(addressType.byteValue());
    switch (addressType) {
        case IPv4:
            byteArrayOutputStream.write(NetUtil.createByteArrayFromIpAddressString(host));
            break;
        case hostname:
            byteArrayOutputStream.write((byte) host.length());
            byteArrayOutputStream.write(host.getBytes(CharsetUtil.US_ASCII));
            break;
        case IPv6:
            byteArrayOutputStream.write(NetUtil.createByteArrayFromIpAddressString(host));
            break;
        default:
            break;
    }
    byteArrayOutputStream.write((short) port);
    return byteArrayOutputStream.toByteArray();
}
项目:moonlight-ss    文件:ShadowSocksRequest.java   
public void encodeAsByteBuf(ByteBuf byteBuf) {
    byteBuf.writeByte(addressType.byteValue());
    switch (addressType) {
        case IPv4:
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        case hostname:
            byteBuf.writeByte(host.length());
            byteBuf.writeBytes(host.getBytes(CharsetUtil.US_ASCII));
            byteBuf.writeShort(port);
            break;
        case IPv6:
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        default:
            break;
    }
}
项目:reactor-netty    文件:InetSocketAddressUtil.java   
private static InetAddress attemptParsingIpString(String hostname) {
    byte[] ipAddressBytes = NetUtil.createByteArrayFromIpAddressString(hostname);

    if (ipAddressBytes != null) {
        try {
            if (ipAddressBytes.length == 4) {
                return Inet4Address.getByAddress(ipAddressBytes);
            }
            else {
                return Inet6Address.getByAddress(null, ipAddressBytes, -1);
            }
        }
        catch (UnknownHostException e) {
            throw new RuntimeException(e); // Should never happen
        }
    }

    return null;
}
项目:reactor-netty    文件:ClientOptions.java   
/**
 * Deep-copy all references from the passed builder into this new
 * {@link NettyOptions} instance.
 *
 * @param builder the ClientOptions builder
 */
protected ClientOptions(ClientOptions.Builder<?> builder){
    super(builder);
    this.proxyOptions = builder.proxyOptions;
    if (Objects.isNull(builder.connectAddress)) {
        if (builder.port >= 0) {
            if (Objects.isNull(builder.host)) {
                this.connectAddress = () -> new InetSocketAddress(NetUtil.LOCALHOST, builder.port);
            }
            else {
                this.connectAddress = () -> InetSocketAddressUtil.createUnresolved(builder.host, builder.port);
            }
        }
        else {
            this.connectAddress = null;
        }
    }
    else {
        this.connectAddress = builder.connectAddress;
    }
    this.poolResources = builder.poolResources;
    this.protocolFamily = builder.protocolFamily;
}
项目:reactor-netty    文件:UdpServerTests.java   
private NetworkInterface findMulticastEnabledIPv4Interface() throws SocketException {
    if (isMulticastEnabledIPv4Interface(NetUtil.LOOPBACK_IF)) {
        return NetUtil.LOOPBACK_IF;
    }

    for (Enumeration<NetworkInterface> ifaces =
         NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
        NetworkInterface iface = ifaces.nextElement();
        if (isMulticastEnabledIPv4Interface(iface)) {
            return iface;
        }
    }

    throw new UnsupportedOperationException(
            "This test requires a multicast enabled IPv4 network interface, but " + "none" + " " + "were found");
}
项目:reactor-netty    文件:TcpServerTests.java   
@Override
public void run() {
    try {
        SocketChannel ch =
                SocketChannel.open(new InetSocketAddress(NetUtil.LOCALHOST, port));
        int len = ch.write(ByteBuffer.wrap(output.getBytes(Charset.defaultCharset())));
        Assertions.assertThat(ch.isConnected()).isTrue();
        data = ByteBuffer.allocate(len);
        int read = ch.read(data);
        Assertions.assertThat(read).isGreaterThan(0);
        data.flip();
        latch.countDown();
    } catch(Exception e) {
        this.e = e;
    }
}
项目:netty4.0.27Learn    文件:TestUtils.java   
/**
 * Return a free port which can be used to bind to
 *
 * @return port
 */
public static int getFreePort() {
    for (int i = 0; i < NUM_CANDIDATES; i ++) {
        final int port = nextCandidatePort();
        final InetSocketAddress wildcardAddr = new InetSocketAddress(port);
        final InetSocketAddress loopbackAddr = new InetSocketAddress(NetUtil.LOCALHOST4, port);

        // Ensure it is possible to bind on wildcard/loopback and tcp/udp.
        if (isTcpPortAvailable(wildcardAddr) &&
            isTcpPortAvailable(loopbackAddr) &&
            isUdpPortAvailable(wildcardAddr) &&
            isUdpPortAvailable(loopbackAddr)) {
            return port;
        }
    }

    throw new RuntimeException("unable to find a free port");
}
项目:netty4.0.27Learn    文件:OioEventLoopTest.java   
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
项目:netty4study    文件:AbstractDatagramTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Entry<Factory<Bootstrap>, Factory<Bootstrap>> e: COMBO) {
            sb = e.getKey().newInstance();
            cb = e.getValue().newInstance();
            addr = new InetSocketAddress(
                    NetUtil.LOCALHOST4, TestUtils.getFreePort());
            sb.localAddress(addr);
            sb.option(ChannelOption.ALLOCATOR, allocator);
            cb.localAddress(0).remoteAddress(addr);
            cb.option(ChannelOption.ALLOCATOR, allocator);
            logger.info(String.format(
                    "Running: %s %d of %d (%s + %s) with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), sb, cb, StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), Bootstrap.class, Bootstrap.class);
                m.invoke(this, sb, cb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty4study    文件:AbstractServerSocketTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Factory<ServerBootstrap> e: COMBO) {
            sb = e.newInstance();
            addr = new InetSocketAddress(
                    NetUtil.LOCALHOST, TestUtils.getFreePort());
            sb.localAddress(addr);
            sb.option(ChannelOption.ALLOCATOR, allocator);
            sb.childOption(ChannelOption.ALLOCATOR, allocator);

            logger.info(String.format(
                    "Running: %s %d of %d (%s) with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), sb, StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), ServerBootstrap.class);
                m.invoke(this, sb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty4study    文件:AbstractClientSocketTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Factory<Bootstrap> e: COMBO) {
            cb = e.newInstance();
            addr = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
            cb.remoteAddress(addr);
            cb.option(ChannelOption.ALLOCATOR, allocator);
            logger.info(String.format(
                    "Running: %s %d of %d with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), Bootstrap.class);
                m.invoke(this, cb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty4study    文件:TestUtils.java   
/**
 * Return a free port which can be used to bind to
 *
 * @return port
 */
public static int getFreePort() {
    for (int i = 0; i < NUM_CANDIDATES; i ++) {
        int port = nextCandidatePort();
        try {
            // Ensure it is possible to bind on both wildcard and loopback.
            ServerSocket ss;
            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(port));
            ss.close();

            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(NetUtil.LOCALHOST, port));
            ss.close();

            return port;
        } catch (IOException e) {
            // ignore
        }
    }

    throw new RuntimeException("unable to find a free port");
}
项目:netty4study    文件:OioEventLoopTest.java   
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
项目:bigio    文件:NetworkUtil.java   
/**
 * Get a random unused port between START_PORT and END_PORT.
 * 
 * @return a random unused port
 * @throws java.net.SocketException in the case where a free port cannot be located.
 */
public static int getFreePort() throws SocketException {
    for (int i = 0; i < NUM_CANDIDATES; i ++) {
        int port = nextCandidatePort();
        try {
            // Ensure it is possible to bind on both wildcard and loopback.
            ServerSocket ss;
            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(port));
            ss.close();

            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(NetUtil.LOCALHOST, port));
            ss.close();

            return port;
        } catch (IOException e) {
            // ignore
        }
    }

    throw new SocketException("unable to find a free port");
}
项目:netty-netty-5.0.0.Alpha1    文件:AbstractDatagramTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Entry<Factory<Bootstrap>, Factory<Bootstrap>> e: COMBO) {
            sb = e.getKey().newInstance();
            cb = e.getValue().newInstance();
            addr = new InetSocketAddress(
                    NetUtil.LOCALHOST4, TestUtils.getFreePort());
            sb.localAddress(addr);
            sb.option(ChannelOption.ALLOCATOR, allocator);
            cb.localAddress(0).remoteAddress(addr);
            cb.option(ChannelOption.ALLOCATOR, allocator);
            logger.info(String.format(
                    "Running: %s %d of %d (%s + %s) with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), sb, cb, StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), Bootstrap.class, Bootstrap.class);
                m.invoke(this, sb, cb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:AbstractServerSocketTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Factory<ServerBootstrap> e: COMBO) {
            sb = e.newInstance();
            addr = new InetSocketAddress(
                    NetUtil.LOCALHOST, TestUtils.getFreePort());
            sb.localAddress(addr);
            sb.option(ChannelOption.ALLOCATOR, allocator);
            sb.childOption(ChannelOption.ALLOCATOR, allocator);

            logger.info(String.format(
                    "Running: %s %d of %d (%s) with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), sb, StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), ServerBootstrap.class);
                m.invoke(this, sb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:AbstractClientSocketTest.java   
protected void run() throws Throwable {
    for (ByteBufAllocator allocator: ALLOCATORS) {
        int i = 0;
        for (Factory<Bootstrap> e: COMBO) {
            cb = e.newInstance();
            addr = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
            cb.remoteAddress(addr);
            cb.option(ChannelOption.ALLOCATOR, allocator);
            logger.info(String.format(
                    "Running: %s %d of %d with %s",
                    testName.getMethodName(), ++ i, COMBO.size(), StringUtil.simpleClassName(allocator)));
            try {
                Method m = getClass().getDeclaredMethod(
                        testName.getMethodName(), Bootstrap.class);
                m.invoke(this, cb);
            } catch (InvocationTargetException ex) {
                throw ex.getCause();
            }
        }
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:TestUtils.java   
/**
 * Return a free port which can be used to bind to
 *
 * @return port
 */
public static int getFreePort() {
    for (int i = 0; i < NUM_CANDIDATES; i ++) {
        int port = nextCandidatePort();
        try {
            // Ensure it is possible to bind on both wildcard and loopback.
            ServerSocket ss;
            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(port));
            ss.close();

            ss = new ServerSocket();
            ss.setReuseAddress(false);
            ss.bind(new InetSocketAddress(NetUtil.LOCALHOST, port));
            ss.close();

            return port;
        } catch (IOException e) {
            // ignore
        }
    }

    throw new RuntimeException("unable to find a free port");
}
项目:netty-netty-5.0.0.Alpha1    文件:OioEventLoopTest.java   
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
项目:centraldogma    文件:CentralDogmaConfig.java   
@Override
public void serialize(ServerPort value,
                      JsonGenerator gen, SerializerProvider serializers) throws IOException {

    final InetSocketAddress localAddr = value.localAddress();
    final int port = localAddr.getPort();
    final String proto = Ascii.toLowerCase(value.protocol().uriText());
    final String host;

    if (localAddr.getAddress().isAnyLocalAddress()) {
        host = "*";
    } else {
        final String hs = localAddr.getHostString();
        if (NetUtil.isValidIpV6Address(hs)) {
            // Try to get the platform-independent consistent IPv6 address string.
            host = NetUtil.toAddressString(localAddr.getAddress());
        } else {
            host = hs;
        }
    }

    gen.writeStartObject();
    gen.writeObjectFieldStart("localAddress");
    gen.writeStringField("host", host);
    gen.writeNumberField("port", port);
    gen.writeEndObject();
    gen.writeStringField("protocol", proto);
    gen.writeEndObject();
}
项目:centraldogma    文件:TokenlessClientLoggerTest.java   
private static ServiceRequestContext newContext(String hostname, String ip) {
    final ServiceRequestContext ctx = Mockito.mock(ServiceRequestContext.class);
    try {
        when(ctx.remoteAddress()).thenReturn(new InetSocketAddress(
                InetAddress.getByAddress(hostname, NetUtil.createByteArrayFromIpAddressString(ip)),
                ThreadLocalRandom.current().nextInt(32768, 65536)));
    } catch (UnknownHostException e) {
        throw new Error(e);
    }
    return ctx;
}
项目:reactor-netty    文件:HttpClientOptions.java   
final String formatSchemeAndHost(String url, boolean ws) {
    if (!url.startsWith(HttpClient.HTTP_SCHEME) && !url.startsWith(HttpClient.WS_SCHEME)) {
        StringBuilder schemeBuilder = new StringBuilder();
        if (ws) {
            schemeBuilder.append(isSecure() ? HttpClient.WSS_SCHEME : HttpClient.WS_SCHEME);
        }
        else {
            schemeBuilder.append(isSecure() ? HttpClient.HTTPS_SCHEME : HttpClient.HTTP_SCHEME);
        }

        final String scheme = schemeBuilder.append("://").toString();
        if (url.startsWith("/")) {
            //consider relative URL, use the base hostname/port or fallback to localhost
            SocketAddress remote = getAddress();

            if (remote instanceof InetSocketAddress) {
                // NetUtil.toSocketAddressString properly handles IPv6 addresses
                return scheme + NetUtil.toSocketAddressString((InetSocketAddress) remote) + url;
            }
            else {
                return scheme + "localhost" + url;
            }
        }
        else {
            //consider absolute URL
            return scheme + url;
        }
    }
    else {
        return url;
    }
}
项目:intellij-ce-playground    文件:ClasspathBootstrap.java   
public static List<String> getBuildProcessApplicationClasspath(boolean isLauncherUsed) {
  final Set<String> cp = ContainerUtil.newHashSet();

  cp.add(getResourcePath(BuildMain.class));

  cp.addAll(PathManager.getUtilClassPath()); // util
  cp.add(getResourcePath(Message.class)); // protobuf
  cp.add(getResourcePath(NetUtil.class)); // netty
  cp.add(getResourcePath(ClassWriter.class));  // asm
  cp.add(getResourcePath(ClassVisitor.class));  // asm-commons
  cp.add(getResourcePath(JpsModel.class));  // jps-model-api
  cp.add(getResourcePath(JpsModelImpl.class));  // jps-model-impl
  cp.add(getResourcePath(JpsProjectLoader.class));  // jps-model-serialization
  cp.add(getResourcePath(AlienFormFileException.class));  // forms-compiler
  cp.add(getResourcePath(GridConstraints.class));  // forms-rt
  cp.add(getResourcePath(CellConstraints.class));  // jGoodies-forms
  cp.add(getResourcePath(NotNullVerifyingInstrumenter.class));  // not-null
  cp.add(getResourcePath(IXMLBuilder.class));  // nano-xml
  cp.add(getResourcePath(SequenceLock.class));  // jsr166
  cp.add(getJpsPluginSystemClassesPath().getAbsolutePath().replace('\\', '/'));

  //don't forget to update layoutCommunityJps() in layouts.gant accordingly

  if (!isLauncherUsed) {
    appendJavaCompilerClasspath(cp);
  }

  try {
    final Class<?> cmdLineWrapper = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
    cp.add(getResourcePath(cmdLineWrapper));  // idea_rt.jar
  }
  catch (Throwable ignored) {
  }

  return ContainerUtil.newArrayList(cp);
}
项目:netty4.0.27Learn    文件:AbstractDatagramTest.java   
@Override
protected void configure(Bootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) {
    addr = new InetSocketAddress(
            NetUtil.LOCALHOST4, TestUtils.getFreePort());
    bootstrap.localAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap2.localAddress(0).remoteAddress(addr);
    bootstrap2.option(ChannelOption.ALLOCATOR, allocator);
}
项目:netty4.0.27Learn    文件:AbstractSctpTest.java   
@Override
protected void configure(ServerBootstrap serverBootstrap, Bootstrap bootstrap, ByteBufAllocator allocator) {
    addr = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    serverBootstrap.localAddress(addr);
    serverBootstrap.option(ChannelOption.ALLOCATOR, allocator);
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
}
项目:netty4.0.27Learn    文件:OioEventLoopTest.java   
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
项目:netty4.0.27Learn    文件:NioSocketChannelTest.java   
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
项目:netty4.0.27Learn    文件:SocksCmdRequest.java   
public SocksCmdRequest(SocksCmdType cmdType, SocksAddressType addressType, String host, int port) {
    super(SocksRequestType.CMD);
    if (cmdType == null) {
        throw new NullPointerException("cmdType");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    switch (addressType) {
        case IPv4:
            if (!NetUtil.isValidIpV4Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv4 address");
            }
            break;
        case DOMAIN:
            if (IDN.toASCII(host).length() > 255) {
                throw new IllegalArgumentException(host + " IDN: " + IDN.toASCII(host) + " exceeds 255 char limit");
            }
            break;
        case IPv6:
            if (!NetUtil.isValidIpV6Address(host)) {
                throw new IllegalArgumentException(host + " is not a valid IPv6 address");
            }
            break;
        case UNKNOWN:
            break;
    }
    if (port <= 0 || port >= 65536) {
        throw new IllegalArgumentException(port + " is not in bounds 0 < x < 65536");
    }
    this.cmdType = cmdType;
    this.addressType = addressType;
    this.host = IDN.toASCII(host);
    this.port = port;
}
项目:netty4.0.27Learn    文件:SocksCmdRequest.java   
@Override
public void encodeAsByteBuf(ByteBuf byteBuf) {
    byteBuf.writeByte(protocolVersion().byteValue());
    byteBuf.writeByte(cmdType.byteValue());
    byteBuf.writeByte(0x00);
    byteBuf.writeByte(addressType.byteValue());
    switch (addressType) {
        case IPv4: {
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        }

        case DOMAIN: {
            byteBuf.writeByte(host.length());
            byteBuf.writeBytes(host.getBytes(CharsetUtil.US_ASCII));
            byteBuf.writeShort(port);
            break;
        }

        case IPv6: {
            byteBuf.writeBytes(NetUtil.createByteArrayFromIpAddressString(host));
            byteBuf.writeShort(port);
            break;
        }
    }
}
项目:netty4.0.27Learn    文件:SocksCmdResponse.java   
/**
 * Constructs new response and includes provided host and port as part of it.
 *
 * @param cmdStatus status of the response
 * @param addressType type of host parameter
 * @param host host (BND.ADDR field) is address that server used when connecting to the target host.
 *             When null a value of 4/8 0x00 octets will be used for IPv4/IPv6 and a single 0x00 byte will be
 *             used for domain addressType. Value is converted to ASCII using {@link IDN#toASCII(String)}.
 * @param port port (BND.PORT field) that the server assigned to connect to the target host
 * @throws NullPointerException in case cmdStatus or addressType are missing
 * @throws IllegalArgumentException in case host or port cannot be validated
 * @see IDN#toASCII(String)
 */
public SocksCmdResponse(SocksCmdStatus cmdStatus, SocksAddressType addressType, String host, int port) {
    super(SocksResponseType.CMD);
    if (cmdStatus == null) {
        throw new NullPointerException("cmdStatus");
    }
    if (addressType == null) {
        throw new NullPointerException("addressType");
    }
    if (host != null) {
        switch (addressType) {
            case IPv4:
                if (!NetUtil.isValidIpV4Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv4 address");
                }
                break;
            case DOMAIN:
                if (IDN.toASCII(host).length() > 255) {
                    throw new IllegalArgumentException(host + " IDN: " +
                            IDN.toASCII(host) + " exceeds 255 char limit");
                }
                break;
            case IPv6:
                if (!NetUtil.isValidIpV6Address(host)) {
                    throw new IllegalArgumentException(host + " is not a valid IPv6 address");
                }
                break;
            case UNKNOWN:
                break;
        }
        host = IDN.toASCII(host);
    }
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException(port + " is not in bounds 0 <= x <= 65535");
    }
    this.cmdStatus = cmdStatus;
    this.addressType = addressType;
    this.host = host;
    this.port = port;
}
项目:netty4.0.27Learn    文件:NativeTest.java   
@Test
public void testAddressIpv4() throws Exception {
    InetSocketAddress inetAddress = new InetSocketAddress(NetUtil.LOCALHOST4, 9999);
    byte[] bytes = new byte[8];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(inetAddress.getAddress().getAddress());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, Native.address(buffer.array(), 0, bytes.length));
}
项目:netty4.0.27Learn    文件:NativeTest.java   
@Test
public void testAddressIpv6() throws Exception {
    Inet6Address address = NetUtil.LOCALHOST6;
    InetSocketAddress inetAddress = new InetSocketAddress(address, 9999);
    byte[] bytes = new byte[24];
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    buffer.put(address.getAddress());
    buffer.putInt(address.getScopeId());
    buffer.putInt(inetAddress.getPort());
    Assert.assertEquals(inetAddress, Native.address(buffer.array(), 0, bytes.length));
}
项目:netty4.0.27Learn    文件:EpollReuseAddrTest.java   
private static ServerBootstrap createServerBootstrap() {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(EpollSocketTestPermutation.EPOLL_BOSS_GROUP, EpollSocketTestPermutation.EPOLL_WORKER_GROUP);
    bootstrap.channel(EpollServerSocketChannel.class);
    bootstrap.childHandler(new DummyHandler());
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    bootstrap.localAddress(address);
    return bootstrap;
}
项目:netty4.0.27Learn    文件:EpollReuseAddrTest.java   
private static Bootstrap createBootstrap() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(EpollSocketTestPermutation.EPOLL_WORKER_GROUP);
    bootstrap.channel(EpollDatagramChannel.class);
    InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST, TestUtils.getFreePort());
    bootstrap.localAddress(address);
    return bootstrap;
}
项目:vertx-mail-client    文件:MailSslTest.java   
@Test
public void mailTestSSLValidCertIpv6(TestContext testContext) {
  // don't run ipv6 tests when ipv4 is preferred, this should enable running the tests
  // on CI where ipv6 is not configured
  Assume.assumeFalse("no ipv6 support", NetUtil.isIpV4StackPreferred() || "true".equals(System.getProperty("test.disableIpV6")));
  this.testContext = testContext;
  startServer(SERVER_JKS);
  final MailConfig config = new MailConfig("::1", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true).setKeyStore(CLIENT_JKS).setKeyStorePassword("password");
  MailClient mailClient = MailClient.createNonShared(vertx, config);
  testSuccess(mailClient);
}
项目:vertx-mail-client    文件:MailSslTest.java   
@Test
public void mailTestSSLValidCertIpv6_2(TestContext testContext) {
  Assume.assumeFalse("no ipv6 support", NetUtil.isIpV4StackPreferred() || "true".equals(System.getProperty("test.disableIpV6")));
  this.testContext = testContext;
  startServer(SERVER_JKS);
  final MailConfig config = new MailConfig("[::1]", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true).setKeyStore(CLIENT_JKS).setKeyStorePassword("password");
  MailClient mailClient = MailClient.createNonShared(vertx, config);
  testSuccess(mailClient);
}
项目:vertx-mail-client    文件:MailSslTest.java   
@Test
public void mailTestSSLValidCertIpv6_3(TestContext testContext) {
  Assume.assumeFalse("no ipv6 support", NetUtil.isIpV4StackPreferred() || "true".equals(System.getProperty("test.disableIpV6")));
  this.testContext = testContext;
  startServer(SERVER_JKS);
  final MailConfig config = new MailConfig("[0000:0000:0000:0000:0000:0000:0000:0001]", 1465, StartTLSOptions.DISABLED, LoginOption.DISABLED)
      .setSsl(true).setKeyStore(CLIENT_JKS).setKeyStorePassword("password");
  MailClient mailClient = MailClient.createNonShared(vertx, config);
  testSuccess(mailClient);
}
项目:DistributedLog4j    文件:TestMulticast.java   
public static void main(String[] args) throws Throwable {
    Bootstrap s = new Bootstrap();
    s.group(sGroup);
    s.channel(NioDatagramChannel.class);

    Bootstrap c = new Bootstrap();
    c.group(cGroup);
    c.channel(NioDatagramChannel.class);

    InetSocketAddress addr = new InetSocketAddress(NetUtil.LOCALHOST4, port);
    s.localAddress(addr);
    c.localAddress(0).remoteAddress(addr);

    testMulticast(s, c);
}
项目:armeria    文件:SniServerTest.java   
@Override
protected void configure(ServerBuilder sb) throws Exception {
    dnsResolver = new InMemoryDnsResolver();
    dnsResolver.add("a.com", NetUtil.LOCALHOST4);
    dnsResolver.add("b.com", NetUtil.LOCALHOST4);
    dnsResolver.add("c.com", NetUtil.LOCALHOST4);
    dnsResolver.add("mismatch.com", NetUtil.LOCALHOST4);
    dnsResolver.add("127.0.0.1", NetUtil.LOCALHOST4);

    final VirtualHostBuilder a = new VirtualHostBuilder("a.com");
    final VirtualHostBuilder b = new VirtualHostBuilder("b.com");
    final VirtualHostBuilder c = new VirtualHostBuilder("c.com");

    a.service("/", new SniTestService("a.com"));
    b.service("/", new SniTestService("b.com"));
    c.service("/", new SniTestService("c.com"));

    a.sslContext(HTTPS, sscA.certificateFile(), sscA.privateKeyFile());
    b.sslContext(HTTPS, sscB.certificateFile(), sscB.privateKeyFile());
    c.sslContext(HTTPS, sscC.certificateFile(), sscC.privateKeyFile());

    sb.virtualHost(a.build());
    sb.virtualHost(b.build());
    sb.defaultVirtualHost(c.build());

    sb.port(0, HTTPS);
}