Convert IPAddress to String for use with Spark.publish()

Hi everyone, I’m a Particle/C newb and am having a tough time accomplishing what I feel should be a very simple goal. I’d like to obtain my localIP (WiFi.localIP();) and publish it as an event to the cloud. I’m having difficulty because the syntax for Spark.publish() expects a char for the data argument, and IPAddress is not of that type: publish(const char *eventName, const char *eventData, Spark_Event_TypeDef eventType=PUBLIC)

Is there an easy way to convert an IPAddress to a String or char array? Here’s some basic code (of what obviously doesn’t work):


void loop() {
  IPAddress myIP = WiFi.localIP();
  Serial.println(myIP); //works totally fine, no conversion needed
  Spark.publish("LocalIP",myIP,60,PRIVATE); //nooope

I tried a number of methods from reading documentation, as well as Google searches and whatnot, but nothing has worked thus far. My programming background is with Ruby, so my first exposure to C/C++ is proving to be challenging. Any insight would be greatly appreciated!

Hi @cwade

I think this thread may help you out:

Here is a similar way–the trick is that IPAddress is indexable via the array operator square brackets:

  IPAddress myIP = WiFi.localIP();
  String ipStr = String(myIP[0])+"."+String(myIP[1])+"."+String(myIP[2])+"."+String(myIP[3]);
  Spark.publish("LocalIP", ipStr, 60,PRIVATE);
1 Like

I just added a change to firmware so you can turn any Printable into a String (IPAddress is Printable):

  IPAddress myIP = WiFi.localIP();
  Spark.publish("LocalIP", String(myIP), PRIVATE);

This will be in the 0.4.5 release, due out on 2 Sept.


Thanks so much guys. @bko’s example did the trick. I searched the community posts and seemed to have missed the one mentioned here. I tried something similar, but with no luck. Haven’t tried the specific example in that post, but good to see some other options. Also, thanks for the heads up on the update, @mdma!

Thank you! I’ve been doing my head in for weeks on this…

So many constant char errors trying to publish a simple temperature value! Have now got it publishing and all i needed was String(…)

1 Like