Android examples for android.net:ConnectivityManager
create Multicast Socket
import java.io.IOException; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import android.content.Context; import android.net.ConnectivityManager; import android.net.DhcpInfo; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; public class Main { private static final int MULTICAST_TTL = 255; 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); }/* www . j a v a 2 s. co m*/ 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("", "isWirelessDirect: probably wireless direct."); return true; } } return false; } private static boolean connectedToEthernet(Context context) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ethInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET); if (ethInfo == null) { return false; } return ethInfo.isConnectedOrConnecting(); } }