From d8b229031342ab3f27dcf9be7e37ac5088c9624e Mon Sep 17 00:00:00 2001 From: Drake Youngkun Min Date: Thu, 24 Nov 2016 16:46:11 +0900 Subject: [PATCH] Add 'fromString(const char*)', 'fromString(const String)' to IPAddress class (#68) --- cores/esp32/IPAddress.cpp | 41 +++++++++++++++++++++++++++++++++++++++ cores/esp32/IPAddress.h | 3 +++ 2 files changed, 44 insertions(+) diff --git a/cores/esp32/IPAddress.cpp b/cores/esp32/IPAddress.cpp index 635c8bf0a..f932d7bf5 100644 --- a/cores/esp32/IPAddress.cpp +++ b/cores/esp32/IPAddress.cpp @@ -79,3 +79,44 @@ String IPAddress::toString() return String(szRet); } +bool IPAddress::fromString(const char *address) +{ + // TODO: add support for "a", "a.b", "a.b.c" formats + + uint16_t acc = 0; // Accumulator + uint8_t dots = 0; + + while (*address) + { + char c = *address++; + if (c >= '0' && c <= '9') + { + acc = acc * 10 + (c - '0'); + if (acc > 255) { + // Value out of [0..255] range + return false; + } + } + else if (c == '.') + { + if (dots == 3) { + // Too much dots (there must be 3 dots) + return false; + } + _address.bytes[dots++] = acc; + acc = 0; + } + else + { + // Invalid char + return false; + } + } + + if (dots != 3) { + // Too few dots (there must be 3 dots) + return false; + } + _address.bytes[3] = acc; + return true; +} \ No newline at end of file diff --git a/cores/esp32/IPAddress.h b/cores/esp32/IPAddress.h index 980be00f7..7c48b6734 100644 --- a/cores/esp32/IPAddress.h +++ b/cores/esp32/IPAddress.h @@ -51,6 +51,9 @@ public: IPAddress(const uint8_t *address); virtual ~IPAddress() {} + bool fromString(const char *address); + bool fromString(const String &address) { return fromString(address.c_str()); } + // Overloaded cast operator to allow IPAddress objects to be used where a pointer // to a four-byte uint8_t array is expected operator uint32_t() const -- GitLab