|
9 | 9 |
|
10 | 10 | import java.net.InetAddress;
|
11 | 11 | import java.net.InetSocketAddress;
|
| 12 | +import java.util.concurrent.ThreadLocalRandom; |
12 | 13 |
|
13 | 14 | public class SimpleDnsServer {
|
14 | 15 |
|
15 | 16 | private final EventLoopGroup group = new NioEventLoopGroup();
|
16 | 17 | private final Channel channel;
|
17 | 18 | private String ip = "127.0.0.1";
|
18 |
| - private final int port = 55; |
| 19 | + private final int port; |
19 | 20 |
|
20 | 21 | public SimpleDnsServer() throws InterruptedException {
|
21 |
| - Bootstrap bootstrap = new Bootstrap(); |
22 |
| - bootstrap.group(group) |
23 |
| - .channel(NioDatagramChannel.class) |
24 |
| - .handler(new ChannelInitializer<>() { |
25 |
| - @Override |
26 |
| - protected void initChannel(Channel ch) throws Exception { |
27 |
| - ch.pipeline().addLast(new DatagramDnsQueryDecoder()); |
28 |
| - ch.pipeline().addLast(new DatagramDnsResponseEncoder()); |
29 |
| - ch.pipeline().addLast(new DnsMessageHandler()); |
30 |
| - } |
31 |
| - }); |
| 22 | + this(ThreadLocalRandom.current().nextInt(50, 1000)); |
| 23 | + } |
| 24 | + |
| 25 | + public SimpleDnsServer(int port) throws InterruptedException { |
| 26 | + Bootstrap bootstrap = new Bootstrap(); |
| 27 | + bootstrap.group(group) |
| 28 | + .channel(NioDatagramChannel.class) |
| 29 | + .handler(new ChannelInitializer<>() { |
| 30 | + @Override |
| 31 | + protected void initChannel(Channel ch) throws Exception { |
| 32 | + ch.pipeline().addLast(new DatagramDnsQueryDecoder()); |
| 33 | + ch.pipeline().addLast(new DatagramDnsResponseEncoder()); |
| 34 | + ch.pipeline().addLast(new DnsMessageHandler()); |
| 35 | + } |
| 36 | + }); |
32 | 37 |
|
33 |
| - ChannelFuture future = bootstrap.bind(port).sync(); |
34 |
| - channel = future.channel(); |
| 38 | + this.port = port; |
| 39 | + ChannelFuture future = bootstrap.bind(port).sync(); |
| 40 | + channel = future.channel(); |
35 | 41 | }
|
36 | 42 |
|
37 | 43 | public InetSocketAddress getAddr() {
|
|
0 commit comments