2012-08-08 935 views
10

在我的类(扩展SimpleChannelHandler)中,我试图获取邮件最初发送来的ip。Netty:在messageReceived中获取远程ip地址

@Override 
public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) throws Exception { 
    String host = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress(); 
    int port = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getPort(); 
    LOG.debug(String.format("host:%s port:%d", host, port)); 

    .. 

这打印ip 10.0.0.1(网关),而不是正确的客户端地址(10.52.45.4)。

有没有什么办法让ip我试图或可能会出现网络配置错误?

+3

只需在较新的netty 4.1.5'((InetSocketAddress)ctx.channel()。remoteAddress())。getAddress()。getHostAddress() – Aaron 2017-04-03 21:19:29

回答

4

我想你会看到网关的IP,因为网关做了某种NAT。如果是这样,你唯一的机会就是在你的协议中包含源IP地址并从那里提取它。

+0

这似乎是这种情况。我决定最好按照你的建议进行操作,并在协议中包含source-ip(或本例中的id)。谢谢。 – northernd 2012-08-14 10:56:00

0

从10.0.0开始的IP地址是内部的,您可能将它连接到同一WiFi路由器上的某些东西。要获得10.52.45.4 ip,您必须连接到路由器外部。 (不要忘记端口转发)