java udp获取对方ip_JAVA NIO 获取udp数据报的 发送方ip

程序是通了,但是没法转发,获取不到对方ip。nio中 udp使用的是DatagramChannel ,但是SelectorKey.channel()转化之后的DatagramChannel,调用getRemoteAddress()获取不到对方的ip信息。

看了下java doc

A selectable channel for datagram-oriented sockets.

A datagram channel is created by invoking one of the open methods of this class. It is not possible to create a channel for an arbitrary, pre-existing datagram socket. A newly-created datagram channel is open but not connected. A datagram channel need not be connected in order for the send and receive methods to be used. A datagram channel may be connected, by invoking its connect method, in order to avoid the overhead of the security checks are otherwise performed as part of every send and receive operation. A datagram channel must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses.

Once connected, a datagram channel remains connected until it is disconnected or closed. Whether or not a datagram channel is connected may be determined by invoking its isConnected method.

这个意思差不多就是DatagramChannel 是面向数据报的,是无连接的,所以不需要知道对面ip。然后就为null了。

但是

在bio中,通过DatagramPacket 是可以获取到对方ip信息的。 所以 ip信息应该是在报文里了。所以我要怎么样才能从报文中拿到这个ip呢?

假如使用nio,默认必须要通过ByteBuf 去读取,这样子就获取不到完整的报文信息了。我服了!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值