I've had the same problem and came up with a solution by the combination of @braden, @user707606 and the mainly the post by Chainfire in this Link.
Post in the link is nice but doesn't really offer any code samples but here it's. First you need to Acquire Multicast Lock, this is needed for some Android devices, didn't try in most of them but it was mentioned in some other posts, so I've included it in my code.
Permission is required, so first, add the permissions into your Manifest file.
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Then the second step is to acquire multicast lock in your method.
/* Acquire MultiCast Lock */
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
And then, find your Wifi Network Interface
/**
* Finds Network Interface of Wifi Ethernet.
*
* @return
*/
public static NetworkInterface findWifiNetworkInterface() {
Enumeration<NetworkInterface> enumeration = null;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface wlan0 = null;
while (enumeration.hasMoreElements()) {
wlan0 = enumeration.nextElement();
if (wlan0.getName().equals("wlan0")) {
return wlan0;
}
}
return null;
}
Later, create a Multicast socket with an available port and set your Wifi NetworkInterface.
MulticastSocket multicastSocket = new MulticastSocket();
/* Set NetworkInterface of MultiCast Socket */
NetworkInterface wifiNetworkInterface = findWifiNetworkInterface();
if (wifiNetworkInterface != null) multicastSocket.setNetworkInterface(wifiNetworkInterface);
Then the rest of your implementation remains the same. And once you are done with Multicast Lock, it's recommended to release it.