Skip to content

Commit c53a72d

Browse files
committed
Fix ipaddress import and parse ipv4 strings
1 parent cdab5e7 commit c53a72d

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

py/circuitpy_mpconfig.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,7 @@ extern const struct _mp_obj_module_t wifi_module;
741741
GAMEPADSHIFT_MODULE \
742742
GNSS_MODULE \
743743
I2CPERIPHERAL_MODULE \
744+
IPADDRESS_MODULE \
744745
JSON_MODULE \
745746
MATH_MODULE \
746747
_EVE_MODULE \

shared-bindings/ipaddress/__init__.c

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
*/
2626

2727
#include "py/objexcept.h"
28+
#include "py/objstr.h"
29+
#include "py/parsenum.h"
2830
#include "py/runtime.h"
2931
#include "shared-bindings/ipaddress/__init__.h"
3032
#include "shared-bindings/ipaddress/IPv4Address.h"
@@ -42,7 +44,32 @@
4244

4345
STATIC mp_obj_t ipaddress_ip_address(mp_obj_t ip_in) {
4446
mp_int_t value;
45-
if (!mp_obj_get_int_maybe(ip_in, &value)) {
47+
if (mp_obj_get_int_maybe(ip_in, &value)) {
48+
// We're done.
49+
} else if (MP_OBJ_IS_STR(ip_in)) {
50+
GET_STR_DATA_LEN(ip_in, str_data, str_len);
51+
size_t period_count = 0;
52+
size_t period_index[4] = {0, 0, 0, str_len};
53+
for (size_t i = 0; i < str_len; i++) {
54+
if (str_data[i] == '.') {
55+
if (period_count < 3) {
56+
period_index[period_count] = i;
57+
}
58+
period_count++;
59+
}
60+
}
61+
if (period_count > 3) {
62+
mp_raise_ValueError(translate("Not a valid IP string."));
63+
}
64+
65+
size_t last_period = 0;
66+
for (size_t i = 0; i < 4; i++) {
67+
mp_obj_t octet = mp_parse_num_integer((const char*) str_data + last_period, period_index[i] - last_period, 10, NULL);
68+
last_period = period_index[i] + 1;
69+
value |= MP_OBJ_SMALL_INT_VALUE(octet) << (24 - i * 8);
70+
71+
}
72+
} else {
4673
mp_raise_ValueError(translate("Only raw int supported for ip."));
4774
}
4875

0 commit comments

Comments
 (0)