1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.ipfilter;
17
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelHandler;
22 import io.netty.channel.ChannelHandlerContext;
23 import io.netty.util.internal.ConcurrentSet;
24
25 import java.net.InetAddress;
26 import java.net.InetSocketAddress;
27 import java.util.Set;
28
29
30
31
32
33 @ChannelHandler.Sharable
34 public class UniqueIpFilter extends AbstractRemoteAddressFilter<InetSocketAddress> {
35
36 private final Set<InetAddress> connected = new ConcurrentSet<InetAddress>();
37
38 @Override
39 protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) throws Exception {
40 final InetAddress remoteIp = remoteAddress.getAddress();
41 if (!connected.add(remoteIp)) {
42 return false;
43 } else {
44 ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
45 @Override
46 public void operationComplete(ChannelFuture future) throws Exception {
47 connected.remove(remoteIp);
48 }
49 });
50 return true;
51 }
52 }
53 }