'Arduino Display Ethernet.localIP()
I'm trying to assign the IP Address of the device to a String variable. When I use Serial.println(Ethernet.localIP()) to test it displays the IP Address in octets. If I use String(Ethernet.localIP()); then it displays it as a decimal.
Is there a way to assign the octet format to a variable?
String MyIpAddress;
void StartNetwork()
{
Print("Initializing Network");
if (Ethernet.begin(mac) == 0) {
while (1) {
Print("Failed to configure Ethernet using DHCP");
delay(10000);
}
}
Serial.println(Ethernet.localIP()); //displays: 192.168.80.134
MyIpAddress = String(Ethernet.localIP());
Serial.println(MyIpAddress); //displays: 2253433024
}
Solution 1:[1]
A more lightweight approach is this:
char* ip2CharArray(IPAddress ip) {
static char a[16];
sprintf(a, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return a;
}
An IP address is, at maximum, 15 characters long, so a 16-character buffer suffices. Making it static ensures memory lifetime, so you can return it safely.
Another approach: the character buffer may be provided by the caller:
void ip2CharArray(IPAddress ip, char* buf) {
sprintf(buf, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
}
Solution 2:[2]
just use toString()display.drawString(0, 30, WiFi.localIP().toString());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | LimpTeaM |
