2012-05-29 44 views
1

我有一個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/如何在Android手機的WiFi網絡中播放

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); 
     } 
+0

和子掩碼...? – nullpotent

+0

網絡掩碼是255.255.255.0。 我編輯了這個問題來添加用於查找廣播地址的代碼。在我的情況下,它是192.168.43.255 – user1030768

回答

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的代碼會更好。

+0

我怎麼知道正確的使用? – BlackBear

相關問題