Reputation: 578
The webserver is running on a ESP32. The Android app is being written in Java. The Android phone & ESP32 are in same local network. The minimum Android version is Lollipop (5.0).
To find the IP (IPv4) of a webserver in local network in order to make further communication by making Http requests (GET & POST) to the webserver. Cannot use static IP & hence need to find the dynamically assigned IP.
ESP32 supports mDNS but on Android, it is only supported from version 12. So, mDNS is being used from Android 12 & above without any problem.
Because mDNS cannot be used on Android below 12, current approach is to get the local IP (Ipv4) of the phone which will be w.x.y.z & then loop over the range w.x.y.0 to w.x.y.255, making a Http request (timeout set to 500ms for each request) to each IP to check if the IP is desired one by comparing the response. This will take forever so; multi-threading is being used which significantly reduces the time but still it is too much (in seconds).
A reliable & faster solution for the problem than the 2nd approach for Android below 12. The solution should work even if the local network is formed via a router or via hotspot of the same Android phone or via hotspot of some different phone.
Thanks in advance.
PS: Cannot implement DNS server or anything like so as the ESP32 is being used in a consumer product & as per the consumer POV, the data should be available from ESP32's webserver in the Android app without any user setup or configuration. Actual solution code is not a requirement (it would be great if you provide one) but a logic or general approach on how to solve this will also be appreciated.
Upvotes: 0
Views: 291
Reputation: 578
After much research, I also came up with the UDP just as mentioned by @Robert in the comment & it works fine. Here is the code for anyone in need.
Android (Java)
byte[] buffer = new byte[BYTE_SIZE];
try (DatagramSocket socket = new DatagramSocket(PORT)) {
socket.setSoTimeout(5000);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String receivedIP = new String(packet.getData(), 0, packet.getLength());
// Rest of the code here to check if 'receivedIP' is desired one or not.
} catch (Exception e) {
e.printStackTrace();
}
ESP32 code
#include <WiFiUdp.h>
// Other includes
WiFiUDP udp;
void setup() {
// After connecting to LAN
udp.begin(PORT);
}
void loop() {
udp.beginPacket("255.255.255.255", PORT);
udp.print(WiFi.localIP());
udp.endPacket();
// Rest of the code
}
Upvotes: 0