2012-08-08 933 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,您必須連接到路由器外部。 (不要忘記端口轉發)