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
}
Turns out that the IPAddress property is an array. One simple way to display the IP address is as follows:
String DisplayAddress(IPAddress address)
{
return String(address[0]) + "." +
String(address[1]) + "." +
String(address[2]) + "." +
String(address[3]);
}
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With