0

How can i convert a String to IPAddress on arduino / esp ?

etc. "192.168.1.2" -> IPAddress(192, 168, 1, 2)

Tried this

void setup() {

  Serial.begin(115200);

  IPAddress apip;

  const char *apipch;
  apipch = "192.168.4.1";

Serial.println(apip.fromString(apipch));

}

void loop() {
  // put your main code here, to run repeatedly:
}

But i just get an output "1"

New contributor
strange_esp is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • There are two possibilities in the link, which one did you use? If it didnt work, you did something wrong, but I can't guess what you did do. Post your code, perferably the shortest possible bit - it does not have to be functional, just the the bit where you get your string (is it a String or a char[] ?) how you implemneted the convert code, and where you call the ip() function. – Msquare Sep 10 at 16:50
  • please do not say didn't work ... instead say this is what happened .... .... "didn't work" is almost meanigless – jsotola Sep 10 at 16:59
  • ip.fromString(s.c_str()); – Juraj Sep 10 at 19:54
  • @Msquare have added an example tried both codes but they gave me a result of 1 – strange_esp Sep 11 at 9:02
  • @jsotola your right sorry, i added code and my result – strange_esp Sep 11 at 9:02
0

The IPAddress class has a member function bool fromString(const char *address).

  • This just gives me a result of 1 sadly – strange_esp Sep 11 at 9:00
  • that is because you don't use it like, don't expect the return value to hold the desired ip, the method operates on a previously defined IPAddress object. – Sim Son yesterday
0

Please check the function into IPAddress.cpp file of line 70 :

bool IPAddress::fromString(const char *address) { 
// TODO: (IPv4) add support for "a", "a.b", "a.b.c" formats    
.... 
}

I think you need to drop the parentheses from the IPAdress ip() in your code, The code should be like below :

Void yourMethod (const char *addr, String ipStr){

IPAdreess ip;
bool i;

i = ip.fromString(ipStr);
    if (i) {
        for (int a = 0; a < 4; a++) {
            addr[a] = ip[a];
          ....
        }
    }
}

Hope this helps.

Your Answer

strange_esp is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.