19
19
#include " NetworkStack.h"
20
20
#include < string.h>
21
21
#include < stdio.h>
22
+ #include " ip4string.h"
22
23
#include " ip6string.h"
23
24
24
25
25
26
26
- static bool ipv4_is_valid (const char *addr)
27
- {
28
- int i = 0 ;
29
-
30
- // Check each digit for [0-9.]
31
- for (; addr[i]; i++) {
32
- if (!(addr[i] >= ' 0' && addr[i] <= ' 9' ) && addr[i] != ' .' ) {
33
- return false ;
34
- }
35
- }
36
-
37
- // Ending with '.' garuntees host
38
- if (i > 0 && addr[i - 1 ] == ' .' ) {
39
- return false ;
40
- }
41
-
42
- return true ;
43
- }
44
-
45
27
static bool ipv6_is_valid (const char *addr)
46
28
{
47
29
// Check each digit for [0-9a-fA-F:]
@@ -62,48 +44,6 @@ static bool ipv6_is_valid(const char *addr)
62
44
return colons >= 2 ;
63
45
}
64
46
65
- static void ipv4_from_address (uint8_t *bytes, const char *addr)
66
- {
67
- int count = 0 ;
68
- int i = 0 ;
69
-
70
- for (; count < NSAPI_IPv4_BYTES; count++) {
71
- unsigned d;
72
- // Not using %hh, since it might be missing in newlib-based toolchains.
73
- // See also: https://git.io/vxiw5
74
- int scanned = sscanf (&addr[i], " %u" , &d);
75
- if (scanned < 1 ) {
76
- return ;
77
- }
78
-
79
- bytes[count] = static_cast <uint8_t >(d);
80
-
81
- for (; addr[i] != ' .' ; i++) {
82
- if (!addr[i]) {
83
- return ;
84
- }
85
- }
86
-
87
- i++;
88
- }
89
- }
90
-
91
- static void ipv6_from_address (uint8_t *bytes, const char *addr)
92
- {
93
- stoip6 (addr, strlen (addr), bytes);
94
- }
95
-
96
- static void ipv4_to_address (char *addr, const uint8_t *bytes)
97
- {
98
- sprintf (addr, " %d.%d.%d.%d" , bytes[0 ], bytes[1 ], bytes[2 ], bytes[3 ]);
99
- }
100
-
101
- static void ipv6_to_address (char *addr, const uint8_t *bytes)
102
- {
103
- ip6tos (bytes, addr);
104
- }
105
-
106
-
107
47
SocketAddress::SocketAddress (nsapi_addr_t addr, uint16_t port)
108
48
{
109
49
_ip_address = NULL ;
@@ -137,13 +77,12 @@ bool SocketAddress::set_ip_address(const char *addr)
137
77
delete[] _ip_address;
138
78
_ip_address = NULL ;
139
79
140
- if (addr && ipv4_is_valid (addr)) {
80
+ if (addr && stoip4 (addr, strlen (addr), _addr. bytes )) {
141
81
_addr.version = NSAPI_IPv4;
142
- ipv4_from_address (_addr.bytes , addr);
143
82
return true ;
144
83
} else if (addr && ipv6_is_valid (addr)) {
145
84
_addr.version = NSAPI_IPv6;
146
- ipv6_from_address (_addr. bytes , addr);
85
+ stoip6 (addr, strlen ( addr), _addr. bytes );
147
86
return true ;
148
87
} else {
149
88
_addr = nsapi_addr_t ();
@@ -186,9 +125,9 @@ const char *SocketAddress::get_ip_address() const
186
125
if (!_ip_address) {
187
126
_ip_address = new char [NSAPI_IP_SIZE];
188
127
if (_addr.version == NSAPI_IPv4) {
189
- ipv4_to_address (_ip_address, _addr.bytes );
128
+ ip4tos ( _addr.bytes , _ip_address );
190
129
} else if (_addr.version == NSAPI_IPv6) {
191
- ipv6_to_address (_ip_address, _addr.bytes );
130
+ ip6tos ( _addr.bytes , _ip_address );
192
131
}
193
132
}
194
133
0 commit comments