'Why doesn't DatagramSocket#receive(DatagramPacket) block with macOS?
With following code,
import java.io.*;
import java.net.*;
class DatagramServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(null);
socket.bind(new InetSocketAddress("127.0.0.1", 0));
System.out.println(socket.getLocalSocketAddress());
while (true) {
// I just need client's address to send back some data!
DatagramPacket packet = new DatagramPacket(new byte[0], 0);
socket.receive(packet);
System.out.println(packet.getSocketAddress());
}
}
}
In Windows it blocks as expected.
> java --version
java 11.0.8 2020-07-14 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.8+10-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.8+10-LTS, mixed mode)
> java DatagramServer
In macOS it doesn't and prints a bunch of received socket addresses.
$ java -version
openjdk version "11.0.14" 2022-01-18
OpenJDK Runtime Environment Temurin-11.0.14+9 (build 11.0.14+9)
OpenJDK 64-Bit Server VM Temurin-11.0.14+9 (build 11.0.14+9, mixed mode)
$ java DatagramServer
/127.0.0.1:61206
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:0
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
/0.0.0.0:15922
...
Is this normal?
Solution 1:[1]
I think @user207421 is right that it might have something to do with your local configuration. On my macbook the first print statement is the only one that gets executed - afterwards, the server blocks.
On second thought, since you bind to 127.0.0.1, the server should be listening only to data that's sent from your local machine, rather than the entire local network. A quick google search didn't help in finding potential causes for this behaviour, but maybe you could try and analyze the traffic yourself using a command like this:
while true; do lsof -lnP +M -i4 | grep '<server-port>'; sleep 1; done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tycl |
