Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - find a server in the network

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?

like image 792
Mark Avatar asked Dec 16 '10 18:12

Mark


People also ask

How do I find servers on my network?

You can get the IP address of the server by running ipconfig /all on a windows machine, and then you can get the MAC address by looking for that IP address using arp -a . You will be granted with the following results. Note that you can replace DHCP SERVER with SERVER and it will display all servers on the network.

How do I find my server on my phone?

How to check what DNS server address you're currently using on Android. Go into Settings and under Wireless & Networks , tap on Wi-Fi. Tap and hold on your current connected Wi-Fi connection, until a pop-up window appears and select Modify Network Config.

Why does my android say Cannot connect to server?

Restart your device. It might sound simple, but sometimes that's all it takes to fix a bad connection. If restarting doesn't work, switch between Wi-Fi and mobile data: Open your Settings app and tap Network & internet or Connections. Depending on your device, these options may be different.


1 Answers

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.

like image 126
Jess Avatar answered Oct 18 '22 02:10

Jess