1

我有一个安卓手机网络,其中一部手机充当服务器。我尝试使用目标 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);
        }
4

1 回答 1

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 Server/Client。如果您发布用于执行 UDP 广播的代码会更好。

于 2012-05-29T17:52:43.657 回答