我必須網絡設備: 1.服務器(變量IP),需要接收一個字符串進一步的東西(例如套接字9999)。此服務器還有另一個套接字(例如8888),它在配對中發送它的設備名稱。 2.客戶端(可變IP)不知道知道服務器的IP,但想給他發送字符串。IP自動發現
在IP C網絡上,我可以遍歷最後一個八位字節(0..255)並檢查Socket 8888是否傳輸某些東西。但在A和B網絡上我沒有機會。有沒有其他解決方案呢? (我可以迭代所有四個八位字節,但這不會是一個優雅的解決方案)。
謝謝!
我必須網絡設備: 1.服務器(變量IP),需要接收一個字符串進一步的東西(例如套接字9999)。此服務器還有另一個套接字(例如8888),它在配對中發送它的設備名稱。 2.客戶端(可變IP)不知道知道服務器的IP,但想給他發送字符串。IP自動發現
在IP C網絡上,我可以遍歷最後一個八位字節(0..255)並檢查Socket 8888是否傳輸某些東西。但在A和B網絡上我沒有機會。有沒有其他解決方案呢? (我可以迭代所有四個八位字節,但這不會是一個優雅的解決方案)。
謝謝!
最適當的方法來做到這一點,如果它們在相同的LAN是:
只有兩個網絡數據包,您知道IP地址。
--EDITED--
廣播:
InetAddress broadcastAddr = SharedFunctions.getNetworkLocalBroadcastAddressdAsInetAddress();
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setBroadcast(true);
System.arraycopy(BROADCAST_SIGNATURE, 0, buffSend, 0, BROADCAST_SIGNATURE.length);
DatagramPacket packet = new DatagramPacket(buffSend, buffSend.length, broadcastAddr, BROADCAST_PORT);
socket.send(packet);
} catch (Exception e) {
e.printStackTrace();
if(socket != null) try {socket.close();} catch (Exception e1) {}
}
public static InetAddress getNetworkLocalBroadcastAddressdAsInetAddress() throws IOException {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if(VERSION.SDK_INT < 9) {
if(!intf.getInetAddresses().nextElement().isLoopbackAddress()){
byte[] quads = intf.getInetAddresses().nextElement().getAddress();
quads[0] = (byte)255;
return InetAddress.getByAddress(quads);
}
}else{
if(!intf.isLoopback()){
List<InterfaceAddress> intfaddrs = intf.getInterfaceAddresses();
return intfaddrs.get(0).getBroadcast(); //return first IP address
}
}
}
return null;
}
要receice廣播:
try {
socketReceiver = new DatagramSocket(BROADCAST_PORT);
socketReceiver.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(buffRecv, buffRecv.length);
while(Thread.currentThread() == cThreadReceiver){
socketReceiver.receive(packet);
//here you receive the packet and can check the sender IP address
}
} catch (Exception e) {
e.printStackTrace();
if(socketReceiver != null) try {socketReceiver.close();} catch (Exception e1) {}
}
你需要做一些修改,但應該開始你在正確的軌道上。
對於發現,通常使用使用UDP數據包的子網廣播。 – Robert
爲什麼此設備試圖連接到服務器地址未知? –