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.contains(remoteIp)) {
42 return false;
43 } else {
44 connected.add(remoteIp);
45 ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
46 @Override
47 public void operationComplete(ChannelFuture future) throws Exception {
48 connected.remove(remoteIp);
49 }
50 });
51 return true;
52 }
53 }
54 }