getting remote ip address in connectionless server

2019-07-14 17:31发布

Currently I've made a connectionless server and I'd like to know a remote ip address of each udp packet.

To do so, I use

addr = ((InetSocketAddress)ctx.getChannel().getRemoteAddress()).getAddress();

in my channel handler such as

public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) throws Exception 

But NullPointerException comes out. In my guess, the channel has been closed after receiving each udp packet because of connectionless channel.

How can I know it in this case?

Thanks~

标签: java netty
2条回答
狗以群分
2楼-- · 2019-07-14 17:54

It is not clear (at least to me) what the ChannelHandlerContext class is that you are referencing.

If you use a DatagramSocket[1], you can use the receive[1] method to read UDP packets. As documented in the receive method[2], the DatagramPacket[3] will have the sender's ip address and port number.

[1] - http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html [2] - http://docs.oracle.com/javase/6/docs/api/java/net/DatagramSocket.html#receive(java.net.DatagramPacket) [3] - http://docs.oracle.com/javase/6/docs/api/java/net/DatagramPacket.html

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-14 18:06

I noticed the same thing, which is that the channel will not provide the remote address, but when you think about it, it's not the channel (or the DatagramSocket it wraps) that even knows about the remote address, but the Datagram itself does, which is the payload. The payload is delivered in a netty MessageEvent, and if you call MessageEvent.getRemoteAddress(), it returns what you want.

查看更多
登录 后发表回答