Arduino: How to get IP Address for a URL
I was revisiting an Arduino program that was setting the real-time clock on an Arduino MKR 1010 using the services of an NTP timeserver. The problem was that the IP address I had been using to lookup the time was not (currently) valid. I soon found an alternative but wondered if I could use a time server URL to lookup a currently valid IP address to pass to a WiFiUDP object instance.
I took a look in the WiFi.cpp file that defines the WiFi class and found a handy function that looked like just the thing.
int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) { return WiFiDrv::getHostByName(aHostname, aResult); }
The following short Arduino program shows how to retrieve the IP address of a URL and store it in an arduino::IPAddress object. [Arduino documentation for IPAddress object.]
#include <WiFiNINA.h> const char* mySSID = SECRET_SSID; // your WiFi SSID const char* myPass = SECRET_PASSWORD; // Your WiFi password templateinline Print &operator<<(Print &obj, T arg) { obj.print(arg); return obj;} void setup() { Serial.begin(115200); while (!Serial) {} connectToWiFi(); testHost(); } void testHost() { IPAddress lookup; int res = WiFi.hostByName("1.uk.pool.ntp.org", lookup); Serial << "Test Lookup\n"; Serial << lookup << '\n'; } void connectToWiFi() { if (WiFi.status() != WL_CONNECTED) { while (WiFi.begin(mySSID, myPass) != WL_CONNECTED) { delay(500); } Serial << "WiFi connected\n"; Serial << "Local IP: " << WiFi.localIP() << '\n'; // confirmation only } } void loop() { }
I accept that the code should check the returned value from WiFi.hostByName() to ensure that the lookup worked correctly.
Comments
Post a Comment