5

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"

7
  • 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
    Commented Sep 10, 2019 at 16:50
  • please do not say didn't work ... instead say this is what happened .... .... "didn't work" is almost meanigless
    – jsotola
    Commented Sep 10, 2019 at 16:59
  • ip.fromString(s.c_str());
    – Juraj
    Commented Sep 10, 2019 at 19:54
  • @Msquare have added an example tried both codes but they gave me a result of 1 Commented Sep 11, 2019 at 9:02
  • 1
    because you print the return value of fromString and not the IP address. Serial.println(apip);
    – Juraj
    Commented Sep 11, 2019 at 9:14

4 Answers 4

6

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

const char *apipch = "192.168.4.1";
IPAddress apip;

if (apip.fromString(apipch)) { // try to parse into the IPAddress
    Serial.println(apip); // print the parsed IPAddress 
} else {
    Serial.println("UnParsable IP");
}
0
1

You could do this:

String myip="192.168.1.2"
IPAddress local_IP;
bool x= local_IP.fromString(myip);
0
0
IPAddress str2IP(String str) {

    IPAddress ret( getIpBlock(0,str),getIpBlock(1,str),getIpBlock(2,str),getIpBlock(3,str) );
    return ret;

}

int getIpBlock(int index, String str) {
    char separator = '.';
    int found = 0;
    int strIndex[] = {0, -1};
    int maxIndex = str.length()-1;
  
    for(int i=0; i<=maxIndex && found<=index; i++){
      if(str.charAt(i)==separator || i==maxIndex){
          found++;
          strIndex[0] = strIndex[1]+1;
          strIndex[1] = (i == maxIndex) ? i+1 : i;
      }
    }
    
    return found>index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
}
-1

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.

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