|
25 | 25 | */
|
26 | 26 |
|
27 | 27 | #include "py/objexcept.h"
|
| 28 | +#include "py/objstr.h" |
| 29 | +#include "py/parsenum.h" |
28 | 30 | #include "py/runtime.h"
|
29 | 31 | #include "shared-bindings/ipaddress/__init__.h"
|
30 | 32 | #include "shared-bindings/ipaddress/IPv4Address.h"
|
|
42 | 44 |
|
43 | 45 | STATIC mp_obj_t ipaddress_ip_address(mp_obj_t ip_in) {
|
44 | 46 | 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 { |
46 | 73 | mp_raise_ValueError(translate("Only raw int supported for ip."));
|
47 | 74 | }
|
48 | 75 |
|
|
0 commit comments