我目前正在開發一款使用SDK> = 16的android應用程序,該應用程序應該能夠在使用WiFi無線電的局域網中發現不同的Android設備(後來也是iOS設備)。本地網絡中的設備發現
我的第一個猜測是在我的Samsung Galaxy S2上使用組播功能:在同一設備發送數據包時才收到數據包。
我的第二個猜測是主動掃描網絡使用有限的IP地址範圍,並等待適當的響應。不幸的是,這意味着網絡使用DHCP來解決IP地址。
以上都不是解決方案。
我爲我的第一個猜想目前的解決方案:
public class MulticastReceiver extends AsyncTask<Activity, Integer, String> {
private static final String host = "224.1.1.1";
private static final int port = 5007;
private static final String TAG = "MulticastReceiver";
protected String doInBackground(Activity... activities) {
WifiManager wm = (WifiManager)activities[0].getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock = wm.createMulticastLock("mydebuginfo");
multicastLock.acquire();
String message = "Nothing";
if (multicastLock.isHeld()) {
Log.i(TAG, "held multicast lock");
}
try {
InetAddress addr = InetAddress.getByName(host);
MulticastSocket socket = new MulticastSocket(port);
socket.setTimeToLive(4);
socket.setReuseAddress(true);
socket.joinGroup(addr);
byte[] buf = new byte[5];
DatagramPacket recv = new DatagramPacket(buf, buf.length, addr, port);
socket.receive(recv);
message = new String(recv.getData());
socket.leaveGroup(addr);
socket.close();
} catch (Exception e) {
message = "ERROR " + e.toString();
}
multicastLock.release();
return message;
}
}
該代碼產生阻塞線socket.receive(RECV);如果我指定一個超時,我會得到一個超時異常。
但是wifi直接意味着你失去了與本地網絡的連接,不是嗎?我仍然希望能夠在發現其他設備的同時訪問互聯網。同樣爲了測試目的,能夠發現運行非android操作系統的本地機器也是很好的。 – anopheles
然後嘗試NSD。掃描不是要走的路,對於網絡管理員來說,它看起來像是一次攻擊。 –
不是NSD在引擎蓋下使用多播嗎? – anopheles