Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
 }
like image 861
Pete Avatar asked Jan 23 '15 22:01

Pete


2 Answers

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]);
}
like image 61
Pete Avatar answered Sep 28 '22 01:09

Pete


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]);
}
like image 40
Nick Lee Avatar answered Sep 27 '22 23:09

Nick Lee