Android - find a server in the network

坚强是说给别人听的谎言 提交于 2019-12-28 08:39:07

问题


I am currently writing a client-server application and I ask myself if there is a better way to find a server in the local network then going trough all the available IP addresses and see if the correct answer is supplied?


回答1:


You might want to look into UDP broadcasts, where your server announces itself and the phone listens for the broadcasts.


There is an example from the Boxee remote project, quoted below.

Getting the Broadcast Address

You need to access the wifi manager to get the DHCP info and construct a broadcast address from that:

InetAddress getBroadcastAddress() throws IOException {
    WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow

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

Sending and Receiving UDP Broadcast Packets

Having constructed the broadcast address, things work as normal. The following code would send the string data over broadcast and then wait for a response:

DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
    getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);

byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);

You could also look into Bonjour/zeroconf, and there is a Java implementation that should work on Android.



来源:https://stackoverflow.com/questions/4464207/android-find-a-server-in-the-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!