Created
March 29, 2017 20:11
-
-
Save mpuz/6a2fc5ce8d88a0a53a1766d66c493413 to your computer and use it in GitHub Desktop.
Android, Java: Multicast check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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