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"

strange_esp
  • 59
  • 1
  • 1
  • 3

4 Answers4

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"); }

ocrdu
  • 1,795
  • 3
  • 12
  • 24
Sim Son
  • 1,878
  • 13
  • 21
1

You could do this:

String myip="192.168.1.2"
IPAddress local_IP;
bool x= local_IP.fromString(myip);
TuLiO
  • 51
  • 3
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.