Java multicast message example on Windows 10, Version 1703 over lo (Software Loopback Interface 1)
is up: true
support multicast: true
is loopback: true
is point 2 point: false
java.net.SocketException: Network is unreachable: Datagram send failed
at java.net.TwoStacksPlainDatagramSocketImpl.send(Native Method)
at java.net.DatagramSocket.send(DatagramSocket.java:693)
at de.dailab.jiactng.MulticastExample.main(MulticastExample.java:42)
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Optional;
import static java.lang.String.format;
public class MulticastExample {
public static void main(String[] args) {
MulticastSocket socket = null;
String address = "226.6.6.7";
int multicastPort = 9999;
InetAddress group = null;
Enumeration<NetworkInterface> networkInterfaces = null;
Optional<NetworkInterface> optLoInterface = Optional.empty();
try {
group = InetAddress.getByName(address);
socket = new MulticastSocket(multicastPort);
socket.setTimeToLive(1);
networkInterfaces = NetworkInterface.getNetworkInterfaces();
socket.joinGroup(group);
if (networkInterfaces.hasMoreElements()) {
optLoInterface = Collections.list(networkInterfaces).stream().filter(ni -> ni.getName().equals("lo")).findFirst();
}
if (optLoInterface.isPresent()) {
final NetworkInterface lo = optLoInterface.get();
System.out.println(format("is up: %b", lo.isUp()));
System.out.println(format("support multicast: %b", lo.supportsMulticast()));
System.out.println(format("is loopback: %b", lo.isLoopback()));
System.out.println(format("is point 2 point: %b", lo.isPointToPoint()));
socket.setNetworkInterface(lo);
byte[] buffer = new Date().toString().getBytes(StandardCharsets.UTF_8);
final DatagramPacket dp = new DatagramPacket(buffer, buffer.length, group, multicastPort);
socket.send(dp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}