Reputation: 5656
I'm trying to read all traffic from UDP port 6610, and I can see the packets in Wireshark. I made a simple reader for this:
public class ReceiveUDP extends Thread {
private int port = 6610;
private byte[] buffer = new byte[256];
private DatagramSocket socket;
private DatagramPacket packet;
public ReceiveUDP() throws SocketException {
socket = new DatagramSocket(port);
packet = new DatagramPacket(buffer, buffer.length);
System.out.println("Succesfull socket / packet creation");
}
@Override
public void run() {
try {
socket.receive(packet);
System.out.println("Succeded!");
} catch (IOException e) {
System.out.println("Failed to receive packet"+e.getCause().getMessage());
}
}
public static void main(String[] args) throws SocketException {
new ReceiveUDP().start();
}
The printout is:
Succesfull socket / packet creation
I.e. the script locks up at socket.receive(packet)
.
Am I missing something?
Upvotes: 3
Views: 2150
Reputation: 5656
Like Joachim Sauer pointed out, the destination IP was not set to my IP. Changing this solved my problem.
Upvotes: 0
Reputation: 2842
It doesn't quite lock on receive()
, it blocks on receive()
. Specifically, it will wait on the receive line until something turns up. For the purpose of debugging and testing, you might use something like:
socket.setSoTimeout(5000); // Block for max 5 seconds
while (true) {
try {
s.receive(packet);
System.out.println("Succeded!");
break;
} catch (SocketTimeoutException ste) {
// Timeout reached, log this and try again.
// Possibly keep track of the total number of tries and give up
// (break) if it exceeds a threshold.
System.out.println("Timeout reached, will try again");
} catch (IOException iox) {
System.out.println("I/O Error: " + iox.getMessage());
break;
}
}
It's generally not a bad idea to use a timeout on your sockets, this prevents your app from waiting indefinitely. Whether this makes sense for your depends on your use case of course.
Upvotes: 1