Getting `Can't assign requested address` java.net.SocketException using Ehcache multicast

This was caused by an IPv6 address being returned from java.net.NetworkInterface.getDefault(). I'm on a Macbook and was using wireless -- p2p0 (used for AirDrop) was returned as the default network interface but my p2p0 only has an IPv6 ether entry (found by running ipconfig).

Two solutions, both of which worked for me (I prefer the first because it works whether you are using a wired or wireless connection)

  1. Start the JVM with -Djava.net.preferIPv4Stack=true. This caused java.net.NetworkInterface.getDefault() to return my vboxnet0 network interface -- not sure what you'll get if you're not running a host-only VM.
  2. Turn off wireless and use a wired connection

A slight variation on the accepted answer: You can also add the following line of code to your java code:

System.setProperty("java.net.preferIPv4Stack", "true");

You need to add certain configurations to Java VM before you can join a Multicast socket in any machine.

First add this line before attempting any connection to make sure you will get only IPv4 addresses:

System.setProperty("java.net.preferIPv4Stack", "true");

In most of the cases your computer has more than one network interface, so you need to choose the correct one:

Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = networkInterfaces.nextElement();
    Enumeration<InetAddress> addressesFromNetworkInterface = networkInterface.getInetAddresses();
    while (addressesFromNetworkInterface.hasMoreElements()) {
        InetAddress inetAddress = addressesFromNetworkInterface.nextElement();
        if (inetAddress.isSiteLocalAddress()
                && !inetAddress.isAnyLocalAddress()
                && !inetAddress.isLinkLocalAddress()
                && !inetAddress.isLoopbackAddress()
                && !inetAddress.isMulticastAddress()) {
            socket.setNetworkInterface(NetworkInterface.getByName(networkInterface.getName()));
        }
    }
}