Frage

While using Datagram Channel I get a PortUnreachableException. This is what my Codes look like : This is the sender side

//Open a non-blocking socket to send data to Receiver
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(10000));
channel.connect(new InetSocketAddress(host,UDPort));

It is this code that gives me : java.net.PortUnreachableException. The parameter "host" is set as:

String host = new String("192.168.1.3");

The Receiver side is this

//Open a Socket to listen for incoming data
DatagramChannel channel = DatagramChannel.open();
channel.connect(new InetSocketAddress(UDPort));
channel.configureBlocking(false);
ByteBuffer buffer =   ByteBuffer.allocate((recvpkt[0].length)*4);
System.out.println("Waiting for packet");
channel.receive(buffer);
System.out.println("Received packet");

I cannot understand why I am getting this exception. I have looked up examples on net and this is how they all suggest the code should be.

UPDATE 1:

As pointed out in the comment by shazin, the binding needs to be done at Receiver and connection at Sender. The updated code for Sender is:

DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(host,UDPort));

For the Receiver:

DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(host,UDPort));

Now the problem is that if "host" is set as "localhost" the program works but if we pass an IP say 10.132.0.30 as "host" the java.net.PortUnreachableException occurs. While the channel.isConnected() option return "true" the channel.write(buffer) command gives an Exception.

UPDATE 2:

The PortUnreachableException is now gone. The only difference in the code now is that I am using selectors to accept connections on the Receiver side. I still do not understand why the error came when selectors were not being used. If anyone stumbles on this question and knows, do post your answer.

War es hilfreich?

Lösung

Try using the following to get the Ip Address

channel.connect(new InetSocketAddress(InetAddress.getByName(host),UDPort));

UDPort must be equal to the port you are using to Bind in Receiver.

Andere Tipps

The code is correct but the port really is unreachable. It's a network connectivity problem, or a no-listener problem, not a coding problem.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top