[英]NoRouteToHostException with DatagramChannel bound to wildcard address
I am having trouble with this combination: I would like to bind both my sending and receiving datagram channels to system-picked port and IP ( not loopback and not localhost). 我在使用这种组合时遇到了麻烦:我想将发送和接收的数据报通道都绑定到系统选择的端口和IP( 不是环回, 也不是 localhost)。 In the following example, this works all fine when I use "old I/O" aka
DatagramSocket
(case 1), but it fails with NoRouteToHostException
using NIO aka DatagramChannel
(case 3). 在以下示例中,当我使用“旧I / O”又称为
DatagramSocket
(情况1)时,此方法一切正常,但使用NIO又称为DatagramChannel
(情况3)时, NoRouteToHostException
而失败。
My API is all based around InterruptibleChannel
and the socket created via new DatagramSocket
doesn't have a channel associated, so I need to get this working with DatagramChannel.open()
. 我的API都基于
InterruptibleChannel
并且通过new DatagramSocket
创建的套接字没有关联的通道,因此我需要使用DatagramChannel.open()
来使其工作。 A stupid workaround is case 2, where I temporarily "connect" the channel. 一种愚蠢的解决方法是情况2,在这里我临时“连接”了通道。 So this might help answer why case 3 fails...
因此,这可能有助于回答案例3失败的原因...
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class Test {
public static void main( String[] args ) {
try { test(); } catch( Exception e ) { e.printStackTrace(); }
}
public static void test() throws IOException {
DatagramChannel tgt = DatagramChannel.open();
tgt.socket().bind( new InetSocketAddress( 0 ));
SocketAddress tgtAddr = tgt.socket().getLocalSocketAddress();
byte[] data = new byte[] { 1, 2, 3, 4 };
System.out.println( "Sending 1..." ); // ok!
DatagramSocket src1 = new DatagramSocket( new InetSocketAddress( 0 ));
src1.send( new DatagramPacket( data, data.length, tgtAddr ));
System.out.println( "Sending 2..." ); // ok!
DatagramChannel src2 = DatagramChannel.open();
src2.socket().bind( new InetSocketAddress( 0 ));
src2.connect( tgtAddr );
ByteBuffer b = ByteBuffer.wrap( data );
src2.write( b );
src2.disconnect();
System.out.println( "Sending 3..." ); // fails!
DatagramChannel src3 = DatagramChannel.open();
src3.socket().bind( new InetSocketAddress( 0 ));
src3.socket().send( new DatagramPacket( data, data.length, tgtAddr ));
}
}
You're trying to send to the address that 'tgt' is bound to, which is the wildcard address. 您正在尝试将 'tgt'绑定到的地址发送到通配符地址。 I'm surprised that it works at all.
我很惊讶它完全起作用。 You have to supply a proper target IP address, not 0.0.0.0.
您必须提供正确的目标IP地址,而不是0.0.0.0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.