Search in sources :

Example 66 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DnsResponseTest method readMalformedResponseTest.

@Test
public void readMalformedResponseTest() {
    final EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
    final ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket);
    try {
        assertThrows(CorruptedFrameException.class, new Executable() {

            @Override
            public void execute() {
                embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
            }
        });
    } finally {
        assertFalse(embedder.finish());
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Executable(org.junit.jupiter.api.function.Executable) Test(org.junit.jupiter.api.Test)

Example 67 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DnsResponseTest method readResponseTest.

@Test
public void readResponseTest() {
    EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
    for (byte[] p : packets) {
        ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p);
        embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
        AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = embedder.readInbound();
        assertThat(envelope, is(instanceOf(DatagramDnsResponse.class)));
        DnsResponse response = envelope.content();
        assertThat(response, is(sameInstance((Object) envelope)));
        ByteBuf raw = Unpooled.wrappedBuffer(p);
        assertThat(response.id(), is(raw.getUnsignedShort(0)));
        assertThat(response.count(DnsSection.QUESTION), is(raw.getUnsignedShort(4)));
        assertThat(response.count(DnsSection.ANSWER), is(raw.getUnsignedShort(6)));
        assertThat(response.count(DnsSection.AUTHORITY), is(raw.getUnsignedShort(8)));
        assertThat(response.count(DnsSection.ADDITIONAL), is(raw.getUnsignedShort(10)));
        envelope.release();
    }
    assertFalse(embedder.finish());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 68 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class DatagramPacketDecoderTest method testDecode.

@Test
public void testDecode() {
    InetSocketAddress recipient = SocketUtils.socketAddress("127.0.0.1", 10000);
    InetSocketAddress sender = SocketUtils.socketAddress("127.0.0.1", 20000);
    ByteBuf content = Unpooled.wrappedBuffer("netty".getBytes(CharsetUtil.UTF_8));
    assertTrue(channel.writeInbound(new DatagramPacket(content, recipient, sender)));
    assertEquals("netty", channel.readInbound());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.jupiter.api.Test)

Example 69 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class PcapWriteHandler method handleUDP.

/**
 * Handle UDP l4
 *
 * @param ctx {@link ChannelHandlerContext} for {@code localAddress} / {@code remoteAddress},
 *            {@link ByteBuf} allocation and {@code fireExceptionCaught}
 * @param msg {@link DatagramPacket} or {@link DatagramChannel}
 */
private void handleUDP(ChannelHandlerContext ctx, Object msg) {
    ByteBuf udpBuf = ctx.alloc().buffer();
    try {
        if (msg instanceof DatagramPacket) {
            // If bytes are 0 and `captureZeroByte` is false, we won't capture this.
            if (((DatagramPacket) msg).content().readableBytes() == 0 && !captureZeroByte) {
                logger.debug("Discarding Zero Byte UDP Packet");
                return;
            }
            DatagramPacket datagramPacket = ((DatagramPacket) msg).duplicate();
            InetSocketAddress srcAddr = datagramPacket.sender();
            InetSocketAddress dstAddr = datagramPacket.recipient();
            // `sender` (local) address. In this case, we'll get source address from Channel.
            if (srcAddr == null) {
                srcAddr = (InetSocketAddress) ctx.channel().localAddress();
            }
            logger.debug("Writing UDP Data of {} Bytes, Src Addr {}, Dst Addr {}", datagramPacket.content().readableBytes(), srcAddr, dstAddr);
            UDPPacket.writePacket(udpBuf, datagramPacket.content(), srcAddr.getPort(), dstAddr.getPort());
            completeUDPWrite(srcAddr, dstAddr, udpBuf, ctx.alloc(), ctx);
        } else if (msg instanceof ByteBuf && ((DatagramChannel) ctx.channel()).isConnected()) {
            // If bytes are 0 and `captureZeroByte` is false, we won't capture this.
            if (((ByteBuf) msg).readableBytes() == 0 && !captureZeroByte) {
                logger.debug("Discarding Zero Byte UDP Packet");
                return;
            }
            ByteBuf byteBuf = ((ByteBuf) msg).duplicate();
            logger.debug("Writing UDP Data of {} Bytes, Src Addr {}, Dst Addr {}", byteBuf.readableBytes(), initiatiorAddr, handlerAddr);
            UDPPacket.writePacket(udpBuf, byteBuf, initiatiorAddr.getPort(), handlerAddr.getPort());
            completeUDPWrite(initiatiorAddr, handlerAddr, udpBuf, ctx.alloc(), ctx);
        } else {
            logger.debug("Discarding Pcap Write for UDP Object: {}", msg);
        }
    } finally {
        udpBuf.release();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf)

Example 70 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project netty by netty.

the class EpollDatagramChannel method scatteringRead.

private boolean scatteringRead(EpollRecvByteAllocatorHandle allocHandle, NativeDatagramPacketArray array, ByteBuf byteBuf, int datagramSize, int numDatagram) throws IOException {
    RecyclableArrayList datagramPackets = null;
    try {
        int offset = byteBuf.writerIndex();
        for (int i = 0; i < numDatagram; i++, offset += datagramSize) {
            if (!array.addWritable(byteBuf, offset, datagramSize)) {
                break;
            }
        }
        allocHandle.attemptedBytesRead(offset - byteBuf.writerIndex());
        NativeDatagramPacketArray.NativeDatagramPacket[] packets = array.packets();
        int received = socket.recvmmsg(packets, 0, array.count());
        if (received == 0) {
            allocHandle.lastBytesRead(-1);
            return false;
        }
        int bytesReceived = received * datagramSize;
        byteBuf.writerIndex(bytesReceived);
        InetSocketAddress local = localAddress();
        if (received == 1) {
            // Single packet fast-path
            DatagramPacket packet = packets[0].newDatagramPacket(byteBuf, local);
            if (!(packet instanceof io.netty.channel.unix.SegmentedDatagramPacket)) {
                processPacket(pipeline(), allocHandle, datagramSize, packet);
                byteBuf = null;
                return true;
            }
        }
        // Its important that we process all received data out of the NativeDatagramPacketArray
        // before we call fireChannelRead(...). This is because the user may call flush()
        // in a channelRead(...) method and so may re-use the NativeDatagramPacketArray again.
        datagramPackets = RecyclableArrayList.newInstance();
        for (int i = 0; i < received; i++) {
            DatagramPacket packet = packets[i].newDatagramPacket(byteBuf.readRetainedSlice(datagramSize), local);
            addDatagramPacketToOut(packet, datagramPackets);
        }
        // Ass we did use readRetainedSlice(...) before we should now release the byteBuf and null it out.
        byteBuf.release();
        byteBuf = null;
        processPacketList(pipeline(), allocHandle, bytesReceived, datagramPackets);
        datagramPackets.recycle();
        datagramPackets = null;
        return true;
    } finally {
        releaseAndRecycle(byteBuf, datagramPackets);
    }
}
Also used : RecyclableArrayList(io.netty.util.internal.RecyclableArrayList) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)75 InetSocketAddress (java.net.InetSocketAddress)45 ByteBuf (io.netty.buffer.ByteBuf)38 Test (org.junit.Test)15 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)14 Channel (io.netty.channel.Channel)8 ChannelFuture (io.netty.channel.ChannelFuture)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 DatagramChannel (io.netty.channel.socket.DatagramChannel)8 ByteBuffer (java.nio.ByteBuffer)6 Test (org.junit.jupiter.api.Test)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 DefaultAddressedEnvelope (io.netty.channel.DefaultAddressedEnvelope)5 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)5 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)5 InetAddress (java.net.InetAddress)5 SocketAddress (java.net.SocketAddress)5 ArrayList (java.util.ArrayList)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AddressedEnvelope (io.netty.channel.AddressedEnvelope)4