Skip to content

Add 'fromString(const char*)', 'fromString(const String)' to IPAddres… #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions cores/esp32/IPAddress.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
3 changes: 3 additions & 0 deletions cores/esp32/IPAddress.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ class IPAddress: public Printable
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
Expand Down