1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.dns;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.AddressedEnvelope;
20 import io.netty.channel.ChannelHandler;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.socket.DatagramPacket;
23 import io.netty.handler.codec.MessageToMessageEncoder;
24
25 import java.net.InetSocketAddress;
26 import java.util.List;
27
28 import static io.netty.util.internal.ObjectUtil.checkNotNull;
29
30
31
32
33
34 @ChannelHandler.Sharable
35 public class DatagramDnsResponseEncoder
36 extends MessageToMessageEncoder<AddressedEnvelope<DnsResponse, InetSocketAddress>> {
37
38 private final DnsRecordEncoder recordEncoder;
39
40
41
42
43 public DatagramDnsResponseEncoder() {
44 this(DnsRecordEncoder.DEFAULT);
45 }
46
47
48
49
50 public DatagramDnsResponseEncoder(DnsRecordEncoder recordEncoder) {
51 this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
52 }
53
54 @Override
55 protected void encode(ChannelHandlerContext ctx,
56 AddressedEnvelope<DnsResponse, InetSocketAddress> in, List<Object> out) throws Exception {
57
58 final InetSocketAddress recipient = in.recipient();
59 final DnsResponse response = in.content();
60 final ByteBuf buf = allocateBuffer(ctx, in);
61
62 DnsMessageUtil.encodeDnsResponse(recordEncoder, response, buf);
63
64 out.add(new DatagramPacket(buf, recipient, null));
65 }
66
67
68
69
70
71 protected ByteBuf allocateBuffer(
72 ChannelHandlerContext ctx,
73 @SuppressWarnings("unused") AddressedEnvelope<DnsResponse, InetSocketAddress> msg) throws Exception {
74 return ctx.alloc().ioBuffer(1024);
75 }
76 }