下面列出了怎么用io.netty.util.NetUtil的API类实例代码及写法,或者点击链接到github查看源代码。
static CharSequence websocketHostValue(URI wsURL) {
int port = wsURL.getPort();
if (port == -1) {
return wsURL.getHost();
}
String host = wsURL.getHost();
if (port == HttpScheme.HTTP.port()) {
return HttpScheme.HTTP.name().contentEquals(wsURL.getScheme())
|| WebSocketScheme.WS.name().contentEquals(wsURL.getScheme()) ?
host : NetUtil.toSocketAddressString(host, port);
}
if (port == HttpScheme.HTTPS.port()) {
return HttpScheme.HTTPS.name().contentEquals(wsURL.getScheme())
|| WebSocketScheme.WSS.name().contentEquals(wsURL.getScheme()) ?
host : NetUtil.toSocketAddressString(host, port);
}
// if the port is not standard (80/443) its needed to add the port to the header.
// See http://tools.ietf.org/html/rfc6454#section-6.2
return NetUtil.toSocketAddressString(host, port);
}
public void testConnectNotExists(Bootstrap cb) throws Throwable {
final Promise<Throwable> promise = ImmediateEventExecutor.INSTANCE.newPromise();
cb.handler(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
promise.trySuccess(cause);
}
});
ChannelFuture future = cb.connect(NetUtil.LOCALHOST, SocketTestPermutation.BAD_PORT);
try {
Channel datagramChannel = future.syncUninterruptibly().channel();
Assert.assertTrue(datagramChannel.isActive());
datagramChannel.writeAndFlush(
Unpooled.copiedBuffer("test", CharsetUtil.US_ASCII)).syncUninterruptibly();
if (!(datagramChannel instanceof OioDatagramChannel)) {
Assert.assertTrue(promise.syncUninterruptibly().getNow() instanceof PortUnreachableException);
}
} finally {
future.channel().close();
}
}
/**
* 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");
}
private void sendConnectCommand(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress raddr = destinationAddress();
Socks5AddressType addrType;
String rhost;
if (raddr.isUnresolved()) {
addrType = Socks5AddressType.DOMAIN;
rhost = raddr.getHostString();
} else {
rhost = raddr.getAddress().getHostAddress();
if (NetUtil.isValidIpV4Address(rhost)) {
addrType = Socks5AddressType.IPv4;
} else if (NetUtil.isValidIpV6Address(rhost)) {
addrType = Socks5AddressType.IPv6;
} else {
throw new ProxyConnectException(
exceptionMessage("unknown address type: " + StringUtil.simpleClassName(rhost)));
}
}
ctx.pipeline().replace(decoderName, decoderName, new Socks5CommandResponseDecoder());
sendToProxyServer(new DefaultSocks5CommandRequest(Socks5CommandType.CONNECT, addrType, rhost, raddr.getPort()));
}
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress raddr = destinationAddress();
final String host = NetUtil.toSocketAddressString(raddr);
FullHttpRequest req = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
host,
Unpooled.EMPTY_BUFFER, false);
req.headers().set(HttpHeaderNames.HOST, host);
if (authorization != null) {
req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
}
if (headers != null) {
req.headers().add(headers);
}
return req;
}
@Override
public void start() throws IOException {
InetSocketAddress address = new InetSocketAddress(NetUtil.LOCALHOST4, 0);
UdpTransport transport = new UdpTransport(address.getHostName(), address.getPort());
setTransports(transport);
DatagramAcceptor acceptor = transport.getAcceptor();
acceptor.setHandler(new DnsProtocolHandler(this, store) {
@Override
public void sessionCreated(IoSession session) throws Exception {
// USe our own codec to support AAAA testing
session.getFilterChain()
.addFirst("codec", new ProtocolCodecFilter(new TestDnsProtocolUdpCodecFactory()));
}
});
((DatagramSessionConfig) acceptor.getSessionConfig()).setReuseAddress(true);
// Start the listener
acceptor.bind();
}
public TestDnsServer(Map<DnsQuestion, DnsResponse> responses,
@Nullable ChannelInboundHandlerAdapter beforeDnsServerHandler) {
this.responses = ImmutableMap.copyOf(responses);
final Bootstrap b = new Bootstrap();
b.channel(TransportType.datagramChannelType(CommonPools.workerGroup()));
b.group(CommonPools.workerGroup());
b.handler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline p = ch.pipeline();
p.addLast(new DatagramDnsQueryDecoder());
p.addLast(new DatagramDnsResponseEncoder());
if (beforeDnsServerHandler != null) {
p.addLast(beforeDnsServerHandler);
}
p.addLast(new DnsServerHandler());
}
});
channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
}
@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();
}
@Override
protected void encode(ChannelHandlerContext ctx, Socks4CommandRequest msg, ByteBuf out) throws Exception {
out.writeByte(msg.version().byteValue());
out.writeByte(msg.type().byteValue());
out.writeShort(msg.dstPort());
if (NetUtil.isValidIpV4Address(msg.dstAddr())) {
out.writeBytes(NetUtil.createByteArrayFromIpAddressString(msg.dstAddr()));
ByteBufUtil.writeAscii(out, msg.userId());
out.writeByte(0);
} else {
out.writeBytes(IPv4_DOMAIN_MARKER);
ByteBufUtil.writeAscii(out, msg.userId());
out.writeByte(0);
ByteBufUtil.writeAscii(out, msg.dstAddr());
out.writeByte(0);
}
}
/**
* Creates a new instance.
*
* @param status the status of the response
* @param dstAddr the {@code DSTIP} field of the response
* @param dstPort the {@code DSTPORT} field of the response
*/
public DefaultSocks4CommandResponse(Socks4CommandStatus status, String dstAddr, int dstPort) {
if (status == null) {
throw new NullPointerException("cmdStatus");
}
if (dstAddr != null) {
if (!NetUtil.isValidIpV4Address(dstAddr)) {
throw new IllegalArgumentException(
"dstAddr: " + dstAddr + " (expected: a valid IPv4 address)");
}
}
if (dstPort < 0 || dstPort > 65535) {
throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 0~65535)");
}
this.status = status;
this.dstAddr = dstAddr;
this.dstPort = dstPort;
}
private static Endpoint create(String host, int port) {
requireNonNull(host, "host");
if (NetUtil.isValidIpV4Address(host)) {
return new Endpoint(host, host, port, DEFAULT_WEIGHT, HostType.IPv4_ONLY);
}
if (NetUtil.isValidIpV6Address(host)) {
final String ipV6Addr;
if (host.charAt(0) == '[') {
// Strip surrounding '[' and ']'.
ipV6Addr = host.substring(1, host.length() - 1);
} else {
ipV6Addr = host;
}
return new Endpoint(ipV6Addr, ipV6Addr, port, DEFAULT_WEIGHT, HostType.IPv6_ONLY);
}
return new Endpoint(InternetDomainName.from(host).toString(),
null, port, DEFAULT_WEIGHT, HostType.HOSTNAME_ONLY);
}
/**
* Format an address into a canonical numeric format.
*
* @param address socket address
* @return formatted address
*/
public static String formatCanonicalAddress(SocketAddress address) {
// Try to return the "raw" address (without resolved host name, etc)
if (address instanceof InetSocketAddress) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
InetAddress inetAddress = inetSocketAddress.getAddress();
// inetAddress could be null if SocketAddress is in an unresolved form
if (inetAddress == null) {
return address.toString();
} else if (inetAddress instanceof Inet6Address) {
return '[' + NetUtil.toAddressString(inetAddress) + "]:" + inetSocketAddress.getPort();
} else {
return NetUtil.toAddressString(inetAddress) + ':' + inetSocketAddress.getPort();
}
}
return address.toString();
}
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testHeadHeadersOnly(WebClient client, SessionProtocol protocol) throws Exception {
assumeThat(protocol).isSameAs(H1C);
final int port = server.httpPort();
try (Socket s = new Socket(NetUtil.LOCALHOST, port)) {
s.setSoTimeout(10000);
final InputStream in = s.getInputStream();
final OutputStream out = s.getOutputStream();
out.write("HEAD /head-headers-only HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
// Should neither be chunked nor have content.
assertThat(new String(ByteStreams.toByteArray(in)))
.isEqualTo("HTTP/1.1 200 OK\r\n" +
"content-type: text/plain; charset=utf-8\r\n" +
"content-length: 6\r\n\r\n");
}
}
private static int findServerId(Map<Integer, ZooKeeperAddress> servers, int currentServerId,
InetAddress addr) {
final String ip = NetUtil.toAddressString(addr, true);
for (Entry<Integer, ZooKeeperAddress> entry : servers.entrySet()) {
final String zkAddr;
try {
zkAddr = NetUtil.toAddressString(InetAddress.getByName(entry.getValue().host()), true);
} catch (UnknownHostException uhe) {
throw new IllegalStateException(
"failed to resolve the IP address of the server name: " + entry.getValue().host());
}
if (zkAddr.equals(ip)) {
final int serverId = entry.getKey().intValue();
if (currentServerId < 0) {
currentServerId = serverId;
} else if (currentServerId != serverId) {
throw new IllegalStateException(
"cannot auto-detect server ID because there are more than one IP address match. " +
"Both server ID " + currentServerId + " and " + serverId +
" have a matching IP address. Consider specifying server ID explicitly.");
}
}
}
return currentServerId;
}
@Benchmark
public void useGetByNameIpv4() {
for (String testEntry : invalidIpV4Hosts.keySet()) {
if (NetUtil.getByName(testEntry, true) != null) {
throw new RuntimeException("error");
}
}
}
@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;
}
}
}
@Benchmark
public void useIsValidIpv6() {
for (String host : invalidIpV6Hosts.keySet()) {
if (NetUtil.isValidIpV6Address(host)) {
throw new RuntimeException("error");
}
}
}
@Benchmark
public void useIsValidIpv4() {
for (String host : invalidIpV4Hosts.keySet()) {
if (NetUtil.isValidIpV4Address(host)) {
throw new RuntimeException("error");
}
}
}
/**
* Validate an address (IPv4, IPv6, Unix Socket)
*
* @param address human-readable address
* @param addrFamily the {@link AddressFamily} to check the address against
* @throws HAProxyProtocolException if the address is invalid
*/
private static void checkAddress(String address, AddressFamily addrFamily) {
if (addrFamily == null) {
throw new NullPointerException("addrFamily");
}
switch (addrFamily) {
case AF_UNSPEC:
if (address != null) {
throw new HAProxyProtocolException("unable to validate an AF_UNSPEC address: " + address);
}
return;
case AF_UNIX:
return;
}
if (address == null) {
throw new NullPointerException("address");
}
switch (addrFamily) {
case AF_IPv4:
if (!NetUtil.isValidIpV4Address(address)) {
throw new HAProxyProtocolException("invalid IPv4 address: " + address);
}
break;
case AF_IPv6:
if (!NetUtil.isValidIpV6Address(address)) {
throw new HAProxyProtocolException("invalid IPv6 address: " + address);
}
break;
default:
throw new Error();
}
}
/**
* Returns a {@link Predicate} which returns {@code true} if the given {@link InetAddress} is in the
* range of a <a href="https://tools.ietf.org/html/rfc4632">Classless Inter-domain Routing (CIDR)</a> block.
*
* @param baseAddress the base {@link InetAddress} of a CIDR notation
* @param subnetMask the subnet mask, e.g. {@code 255.255.255.0}
*/
public static Predicate<InetAddress> ofCidr(InetAddress baseAddress, String subnetMask) {
requireNonNull(baseAddress, "baseAddress");
requireNonNull(subnetMask, "subnetMask");
checkArgument(NetUtil.isValidIpV4Address(subnetMask),
"subnetMask: %s (expected: an IPv4 address string)", subnetMask);
final int maskBits = toMaskBits(subnetMask);
return ofCidr(baseAddress, maskBits, maskBits + 96);
}
protected SocketAddress newSocketAddress() {
// We use LOCALHOST4 as we use InternetProtocolFamily.IPv4 when creating the DatagramChannel and its
// not supported to bind to and IPV6 address in this case.
//
// See also http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/e74259b3eadc/
// src/share/classes/sun/nio/ch/DatagramChannelImpl.java#l684
return new InetSocketAddress(NetUtil.LOCALHOST4, 0);
}
private static DnsRecord newMappedAddressRecord(String name, String ipV4Addr) {
final ByteBuf content = Unpooled.buffer();
content.writeZero(10);
content.writeShort(0xFFFF);
content.writeBytes(NetUtil.createByteArrayFromIpAddressString(ipV4Addr));
return new DefaultDnsRawRecord(name, AAAA, 60, content);
}
private static List<DnsQuestion> newQuestions(
String hostname, @Nullable ResolvedAddressTypes resolvedAddressTypes) {
if (resolvedAddressTypes == null) {
if (NetUtil.isIpV4StackPreferred() || !anyInterfaceSupportsIpV6()) {
resolvedAddressTypes = ResolvedAddressTypes.IPV4_ONLY;
} else {
resolvedAddressTypes = ResolvedAddressTypes.IPV4_PREFERRED;
}
}
final ImmutableList.Builder<DnsQuestion> builder = ImmutableList.builder();
switch (resolvedAddressTypes) {
case IPV4_ONLY:
case IPV4_PREFERRED:
case IPV6_PREFERRED:
builder.add(DnsQuestionWithoutTrailingDot.of(hostname, DnsRecordType.A));
break;
}
switch (resolvedAddressTypes) {
case IPV6_ONLY:
case IPV4_PREFERRED:
case IPV6_PREFERRED:
builder.add(DnsQuestionWithoutTrailingDot.of(hostname, DnsRecordType.AAAA));
break;
}
return builder.build();
}
private static void testConnectRefused0(Bootstrap cb, boolean halfClosure) throws Throwable {
final Promise<Error> errorPromise = GlobalEventExecutor.INSTANCE.newPromise();
ChannelHandler handler = new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
errorPromise.setFailure(new AssertionError("should have never been called"));
}
};
cb.handler(handler);
cb.option(ChannelOption.ALLOW_HALF_CLOSURE, halfClosure);
ChannelFuture future = cb.connect(NetUtil.LOCALHOST, UNASSIGNED_PORT).awaitUninterruptibly();
assertThat(future.cause(), is(instanceOf(ConnectException.class)));
assertThat(errorPromise.cause(), is(nullValue()));
}
@Override
protected void configure(ServerBootstrap serverBootstrap, Bootstrap bootstrap, ByteBufAllocator allocator) {
serverBootstrap.localAddress(new InetSocketAddress(NetUtil.LOCALHOST, 0));
serverBootstrap.option(ChannelOption.ALLOCATOR, allocator);
serverBootstrap.childOption(ChannelOption.ALLOCATOR, allocator);
bootstrap.option(ChannelOption.ALLOCATOR, allocator);
}
private static void testInitialMessage(InetSocketAddress socketAddress, String hostPort,
HttpHeaders headers) throws Exception {
InetSocketAddress proxyAddress = new InetSocketAddress(NetUtil.LOCALHOST, 8080);
ChannelPromise promise = mock(ChannelPromise.class);
verifyNoMoreInteractions(promise);
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
when(ctx.connect(same(proxyAddress), isNull(InetSocketAddress.class), same(promise))).thenReturn(promise);
HttpProxyHandler handler = new HttpProxyHandler(new InetSocketAddress(NetUtil.LOCALHOST, 8080), headers);
handler.connect(ctx, socketAddress, null, promise);
FullHttpRequest request = (FullHttpRequest) handler.newInitialMessage(ctx);
try {
assertEquals(HttpVersion.HTTP_1_1, request.protocolVersion());
assertEquals(hostPort, request.uri());
HttpHeaders actualHeaders = request.headers();
assertEquals(hostPort, actualHeaders.get(HttpHeaderNames.HOST));
if (headers != null) {
// The actual request header is a strict superset of the custom header
for (String name : headers.names()) {
assertEquals(headers.getAll(name), actualHeaders.getAll(name));
}
}
} finally {
request.release();
}
verify(ctx).connect(proxyAddress, null, promise);
}
private IntObjectMap<DnsQueryContext> getOrCreateContextMap(InetSocketAddress nameServerAddr) {
synchronized (map) {
final IntObjectMap<DnsQueryContext> contexts = map.get(nameServerAddr);
if (contexts != null) {
return contexts;
}
final IntObjectMap<DnsQueryContext> newContexts = new IntObjectHashMap<DnsQueryContext>();
final InetAddress a = nameServerAddr.getAddress();
final int port = nameServerAddr.getPort();
map.put(nameServerAddr, newContexts);
if (a instanceof Inet4Address) {
// Also add the mapping for the IPv4-compatible IPv6 address.
final Inet4Address a4 = (Inet4Address) a;
if (a4.isLoopbackAddress()) {
map.put(new InetSocketAddress(NetUtil.LOCALHOST6, port), newContexts);
} else {
map.put(new InetSocketAddress(toCompactAddress(a4), port), newContexts);
}
} else if (a instanceof Inet6Address) {
// Also add the mapping for the IPv4 address if this IPv6 address is compatible.
final Inet6Address a6 = (Inet6Address) a;
if (a6.isLoopbackAddress()) {
map.put(new InetSocketAddress(NetUtil.LOCALHOST4, port), newContexts);
} else if (a6.isIPv4CompatibleAddress()) {
map.put(new InetSocketAddress(toIPv4Address(a6), port), newContexts);
}
}
return newContexts;
}
}
@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);
}
/**
* Hook designed for extensibility so one can pass a different cache on each resolution attempt
* instead of using the global one.
*/
protected void doResolveAll(String inetHost,
DnsRecord[] additionals,
Promise<List<InetAddress>> promise,
DnsCache resolveCache) throws Exception {
if (inetHost == null || inetHost.isEmpty()) {
// If an empty hostname is used we should use "localhost", just like InetAddress.getAllByName(...) does.
promise.setSuccess(Collections.singletonList(loopbackAddress()));
return;
}
final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
if (bytes != null) {
// The unresolvedAddress was created via a String that contains an ipaddress.
promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes)));
return;
}
final String hostname = hostname(inetHost);
InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
if (hostsFileEntry != null) {
promise.setSuccess(Collections.singletonList(hostsFileEntry));
return;
}
if (!doResolveAllCached(hostname, additionals, promise, resolveCache)) {
doResolveAllUncached(hostname, additionals, promise, resolveCache);
}
}
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;
}