Skip to content

Instantly share code, notes, and snippets.

@mpuz
Created March 29, 2017 20:11
Show Gist options
  • Save mpuz/6a2fc5ce8d88a0a53a1766d66c493413 to your computer and use it in GitHub Desktop.
Save mpuz/6a2fc5ce8d88a0a53a1766d66c493413 to your computer and use it in GitHub Desktop.
Android, Java: Multicast check
/** 
* Ensures that the caller receives an usable multicast socket. 
* In case the network configuration does not have a default gateway 
* set, the multicast socket might not work. This is the case when 
* the device is connected to a Wireless Direct printer. In that 
* cases, force a network interface into the socket. 
* @return A ready-to-use multicast socket. 
*/ 
public static MulticastSocket createMulticastSocket(Context context)
throws UnknownHostException, SocketException, IOException { 
MulticastSocket multicastSocket = new MulticastSocket();
 
if (connectedToEthernet(context)) {
NetworkInterface netIf = NetworkInterface.getByName("eth0");
if (netIf != null)
multicastSocket.setNetworkInterface(netIf);
else if (isWirelessDirect(context)) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int intaddr = wifiInfo.getIpAddress();
byte[] byteaddr = new byte[] {
(byte) (intaddr & 0xff),
(byte) (intaddr >> 8 & 0xff),
(byte) (intaddr >> 16 & 0xff),
(byte) (intaddr >> 24 & 0xff)};
InetAddress addr = InetAddress.getByAddress(byteaddr);
NetworkInterface netIf = NetworkInterface.getByInetAddress(addr);
 
multicastSocket.setNetworkInterface(netIf);
multicastSocket.setTimeToLive(MULTICAST_TTL);
return multicastSocket;
 
public static boolean isWirelessDirect(Context context) {
ConnectivityManager connManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
 
if (netInfo != null && netInfo.isConnected() && (netInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
 
if ((dhcpInfo != null) && (dhcpInfo.gateway == 0)) {
Log.d(TAG, "isWirelessDirect: probably wireless direct.");
return true; 
return false; 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment