@Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        if (acceptForeignIp) {
            return;
        }

        // the anonymous access is enabled by default, permission level is PUBLIC
        // if allow anonymous access, return
        if (qosConfiguration.isAllowAnonymousAccess()) {
            return;
        }

        final InetAddress inetAddress = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress();
        // loopback address, return
        if (inetAddress.isLoopbackAddress()) {
            return;
        }

        // the ip is in the whitelist, return
        if (checkForeignIpInWhiteList(inetAddress)) {
            return;
        }

        ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR
                        + "Foreign Ip Not Permitted, Consider Config It In Whitelist." + QosConstants.BR_STR)
                .getBytes());
        ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE);
    }
@Test
    void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteList() throws Exception {
        ChannelHandlerContext context = mock(ChannelHandlerContext.class);
        Channel channel = mock(Channel.class);
        when(context.channel()).thenReturn(channel);
        InetAddress addr = mock(InetAddress.class);
        when(addr.isLoopbackAddress()).thenReturn(false);
        when(addr.getHostAddress()).thenReturn("179.23.44.1");
        InetSocketAddress address = new InetSocketAddress(addr, 12345);
        when(channel.remoteAddress()).thenReturn(address);
        ChannelFuture future = mock(ChannelFuture.class);
        when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future);
        ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder()
                .acceptForeignIp(false)
                .acceptForeignIpWhitelist("175.23.44.1 ,  192.168.1.192/26")
                .anonymousAccessPermissionLevel(PermissionLevel.NONE.name())
                .build());

        handler.handlerAdded(context);
        ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class);
        verify(context).writeAndFlush(captor.capture());
        assertThat(
                new String(captor.getValue().array()),
                containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist"));
        verify(future).addListener(ChannelFutureListener.CLOSE);
    }