如何在Android手机的wifi网络中播放

时间:2012-05-29 17:21:17

标签: android sockets network-programming android-wifi

我有一个Android手机网络,其中一部手机充当服务器。我尝试使用目标IP作为'255.255.255.255.'进行广播。但它无法发送消息。我给下面的logcat。服务器IP为192.168.43.1。我也试过了'192.168.43.255'。但它也最终徒劳无功。对于代码,我提到了http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

05-30 20:17:40.970: E/ClientActivity(698): java.net.UnknownHostException: /192.168.43.255
05-30 20:17:40.970: E/ClientActivity(698):  at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-30 20:17:40.970: E/ClientActivity(698):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-30 20:17:40.970: E/ClientActivity(698):  at java.net.InetAddress.getByName(InetAddress.java:325)
05-30 20:17:40.970: E/ClientActivity(698):  at project.android.aec.ConnectActivity$ClientThread.run(ConnectActivity.java:139)
05-30 20:17:40.970: E/ClientActivity(698):  at java.lang.Thread.run(Thread.java:1019)

以下是用于获取广播IP的代码

   private InetAddress getBroadcastAddress() throws IOException {
        mWifi= (WifiManager) getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcp = mWifi.getDhcpInfo();
        if (dhcp == null) {
          Log.d("BCast Address Fetch", "Could not get dhcp info");
          return null;
        }

        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
        byte[] quads = new byte[4];
        for (int k = 0; k < 4; k++)
          quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
        return InetAddress.getByAddress(quads);
        }

1 个答案:

答案 0 :(得分:2)

这是我用来获取广播地址

for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
 NetworkInterface intf = en.nextElement();
 for (InterfaceAddress address : intf.getInterfaceAddresses()) {
   System.out.println(address.getBroadcast().toString().substring(1));;
 }
}

参考链接中的代码是一个简单的TCP服务器/客户端。如果您发布用于执行UDP BroadCast的代码会更好。