如何拒绝Netty中的传入连接? [英] How to refuse incoming connections in Netty?

查看:155
本文介绍了如何拒绝Netty中的传入连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Netty TCP服务器,我想有选择地拒绝/拒绝传入连接尝试(基于他们的远程地址)。我想我必须使用 ServerBootstrap.setParentHandler(ChannelHandler),但我该如何处理 ChannelHandler ?我处理什么事?我如何拒绝连接?

I have a Netty TCP server, and I want to reject/refuse incoming connection attempts selectively (based on their remote address). I guess I have to use ServerBootstrap.setParentHandler(ChannelHandler), but what do I do in the ChannelHandler? What event am I handling? How do I refuse the connection?

推荐答案

正如Norman所说,没有办法拒绝连接,但你可以关闭它立即将Netty的IpFilterHandler添加到服务器管道作为第一个处理程序。它也将停止传播用于过滤连接的上游信道状态事件。

As Norman said, there is no way to refuse the connection, but you can close it immediately by adding a Netty's IpFilterHandler to server pipeline as the first handler. It will also stop propagating the upstream channel state events for filtered connection too.

@ChannelHandler.Sharable
public class MyFilterHandler extends IpFilteringHandlerImpl {
  private final Set<InetSocketAddress> deniedRemoteAddress;

  public MyFilterHandler(Set<InetSocketAddress> deniedRemoteAddress) {
    this.deniedRemoteAddress = deniedRemoteAddress;
  }

  @Override
  protected boolean accept(ChannelHandlerContext ctx, ChannelEvent e, InetSocketAddress inetSocketAddress) throws Exception {
    return !deniedRemoteAddress.contains(inetSocketAddress);
  }
}

如果您有要阻止的IP地址模式列表,你可以使用IpFilterRuleHandler,

if you have list of patterns of IP address to block, you can use IpFilterRuleHandler,

//Example: allow only localhost:
new IPFilterRuleHandler().addAll(new IpFilterRuleList("+n:localhost, -n:*"))

这篇关于如何拒绝Netty中的传入连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆