Skip to content

Commit 4574f2a

Browse files
committed
Fixing IPAddress::fromString for '1.1.1.' as well as '...'
1 parent 4f67378 commit 4574f2a

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

api/IPAddress.cpp

+11-3
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,15 @@ bool IPAddress::fromString(const char *address)
4949
{
5050
// TODO: add support for "a", "a.b", "a.b.c" formats
5151

52-
uint16_t acc = 0; // Accumulator
52+
int16_t acc = -1; // Accumulator
5353
uint8_t dots = 0;
5454

5555
while (*address)
5656
{
5757
char c = *address++;
5858
if (c >= '0' && c <= '9')
5959
{
60-
acc = acc * 10 + (c - '0');
60+
acc = (acc < 0) ? (c - '0') : acc * 10 + (c - '0');
6161
if (acc > 255) {
6262
// Value out of [0..255] range
6363
return false;
@@ -69,8 +69,12 @@ bool IPAddress::fromString(const char *address)
6969
// Too much dots (there must be 3 dots)
7070
return false;
7171
}
72+
if (acc < 0) {
73+
/* No value between dots, e.g. '1..' */
74+
return false;
75+
}
7276
_address.bytes[dots++] = acc;
73-
acc = 0;
77+
acc = -1;
7478
}
7579
else
7680
{
@@ -83,6 +87,10 @@ bool IPAddress::fromString(const char *address)
8387
// Too few dots (there must be 3 dots)
8488
return false;
8589
}
90+
if (acc < 0) {
91+
/* No value between dots, e.g. '1..' */
92+
return false;
93+
}
8694
_address.bytes[3] = acc;
8795
return true;
8896
}

test/src/IPAddress/test_fromString.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ TEST_CASE ("Extract valid IP address 'fromString(const String &)'", "[IPAddress-
4141
REQUIRE(ip[3] == 2);
4242
}
4343

44-
4544
TEST_CASE ("Extract invalid IP address 'fromString(const char *)'", "[IPAddress-fromString-03]")
4645
{
4746
arduino::IPAddress ip;
@@ -53,6 +52,7 @@ TEST_CASE ("Extract invalid IP address 'fromString(const char *)'", "[IPAddress-
5352
REQUIRE(ip.fromString("1.1.") == false);
5453
REQUIRE(ip.fromString("1.1.1") == false);
5554
REQUIRE(ip.fromString("1.1.1.") == false);
55+
REQUIRE(ip.fromString("...") == false);
5656
REQUIRE(ip.fromString("256.1.1.1") == false);
5757
REQUIRE(ip.fromString("a.1.1.1") == false);
5858
REQUIRE(ip.fromString("-.1.1.1") == false);

0 commit comments

Comments
 (0)