5

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
 }
Pete
  • 2,393
  • 2
  • 24
  • 31

3 Answers3

6

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]);
}
Pete
  • 2,393
  • 2
  • 24
  • 31
2

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]);
}
Nick Lee
  • 5,639
  • 3
  • 27
  • 35
0

just use toString()
display.drawString(0, 30, WiFi.localIP().toString());

LimpTeaM
  • 31
  • 8