xref: /btstack/3rd-party/lwip/core/src/core/ipv4/ip4_addr.c (revision 97dc5e692c7d94a280158af58036a0efee5b0e56)
1 /**
2  * @file
3  * This is the IPv4 address tools implementation.
4  *
5  */
6 
7 /*
8  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * This file is part of the lwIP TCP/IP stack.
34  *
35  * Author: Adam Dunkels <[email protected]>
36  *
37  */
38 
39 #include "lwip/opt.h"
40 
41 #if LWIP_IPV4
42 
43 #include "lwip/ip_addr.h"
44 #include "lwip/netif.h"
45 
46 /* used by IP4_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
47 const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY);
48 const ip_addr_t ip_addr_broadcast = IPADDR4_INIT(IPADDR_BROADCAST);
49 
50 /**
51  * Determine if an address is a broadcast address on a network interface
52  *
53  * @param addr address to be checked
54  * @param netif the network interface against which the address is checked
55  * @return returns non-zero if the address is a broadcast address
56  */
57 u8_t
ip4_addr_isbroadcast_u32(u32_t addr,const struct netif * netif)58 ip4_addr_isbroadcast_u32(u32_t addr, const struct netif *netif)
59 {
60   ip4_addr_t ipaddr;
61   ip4_addr_set_u32(&ipaddr, addr);
62 
63   /* all ones (broadcast) or all zeroes (old skool broadcast) */
64   if ((~addr == IPADDR_ANY) ||
65       (addr == IPADDR_ANY)) {
66     return 1;
67     /* no broadcast support on this network interface? */
68   } else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) {
69     /* the given address cannot be a broadcast address
70      * nor can we check against any broadcast addresses */
71     return 0;
72     /* address matches network interface address exactly? => no broadcast */
73   } else if (addr == ip4_addr_get_u32(netif_ip4_addr(netif))) {
74     return 0;
75     /*  on the same (sub) network... */
76   } else if (ip4_addr_netcmp(&ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif))
77              /* ...and host identifier bits are all ones? =>... */
78              && ((addr & ~ip4_addr_get_u32(netif_ip4_netmask(netif))) ==
79                  (IPADDR_BROADCAST & ~ip4_addr_get_u32(netif_ip4_netmask(netif))))) {
80     /* => network broadcast address */
81     return 1;
82   } else {
83     return 0;
84   }
85 }
86 
87 /** Checks if a netmask is valid (starting with ones, then only zeros)
88  *
89  * @param netmask the IPv4 netmask to check (in network byte order!)
90  * @return 1 if the netmask is valid, 0 if it is not
91  */
92 u8_t
ip4_addr_netmask_valid(u32_t netmask)93 ip4_addr_netmask_valid(u32_t netmask)
94 {
95   u32_t mask;
96   u32_t nm_hostorder = lwip_htonl(netmask);
97 
98   /* first, check for the first zero */
99   for (mask = 1UL << 31 ; mask != 0; mask >>= 1) {
100     if ((nm_hostorder & mask) == 0) {
101       break;
102     }
103   }
104   /* then check that there is no one */
105   for (; mask != 0; mask >>= 1) {
106     if ((nm_hostorder & mask) != 0) {
107       /* there is a one after the first zero -> invalid */
108       return 0;
109     }
110   }
111   /* no one after the first zero -> valid */
112   return 1;
113 }
114 
115 /**
116  * Ascii internet address interpretation routine.
117  * The value returned is in network order.
118  *
119  * @param cp IP address in ascii representation (e.g. "127.0.0.1")
120  * @return ip address in network order
121  */
122 u32_t
ipaddr_addr(const char * cp)123 ipaddr_addr(const char *cp)
124 {
125   ip4_addr_t val;
126 
127   if (ip4addr_aton(cp, &val)) {
128     return ip4_addr_get_u32(&val);
129   }
130   return (IPADDR_NONE);
131 }
132 
133 /**
134  * Check whether "cp" is a valid ascii representation
135  * of an Internet address and convert to a binary address.
136  * Returns 1 if the address is valid, 0 if not.
137  * This replaces inet_addr, the return value from which
138  * cannot distinguish between failure and a local broadcast address.
139  *
140  * @param cp IP address in ascii representation (e.g. "127.0.0.1")
141  * @param addr pointer to which to save the ip address in network order
142  * @return 1 if cp could be converted to addr, 0 on failure
143  */
144 int
ip4addr_aton(const char * cp,ip4_addr_t * addr)145 ip4addr_aton(const char *cp, ip4_addr_t *addr)
146 {
147   u32_t val;
148   u8_t base;
149   char c;
150   u32_t parts[4];
151   u32_t *pp = parts;
152 
153   c = *cp;
154   for (;;) {
155     /*
156      * Collect number up to ``.''.
157      * Values are specified as for C:
158      * 0x=hex, 0=octal, 1-9=decimal.
159      */
160     if (!lwip_isdigit(c)) {
161       return 0;
162     }
163     val = 0;
164     base = 10;
165     if (c == '0') {
166       c = *++cp;
167       if (c == 'x' || c == 'X') {
168         base = 16;
169         c = *++cp;
170       } else {
171         base = 8;
172       }
173     }
174     for (;;) {
175       if (lwip_isdigit(c)) {
176         val = (val * base) + (u32_t)(c - '0');
177         c = *++cp;
178       } else if (base == 16 && lwip_isxdigit(c)) {
179         val = (val << 4) | (u32_t)(c + 10 - (lwip_islower(c) ? 'a' : 'A'));
180         c = *++cp;
181       } else {
182         break;
183       }
184     }
185     if (c == '.') {
186       /*
187        * Internet format:
188        *  a.b.c.d
189        *  a.b.c   (with c treated as 16 bits)
190        *  a.b (with b treated as 24 bits)
191        */
192       if (pp >= parts + 3) {
193         return 0;
194       }
195       *pp++ = val;
196       c = *++cp;
197     } else {
198       break;
199     }
200   }
201   /*
202    * Check for trailing characters.
203    */
204   if (c != '\0' && !lwip_isspace(c)) {
205     return 0;
206   }
207   /*
208    * Concoct the address according to
209    * the number of parts specified.
210    */
211   switch (pp - parts + 1) {
212 
213     case 0:
214       return 0;       /* initial nondigit */
215 
216     case 1:             /* a -- 32 bits */
217       break;
218 
219     case 2:             /* a.b -- 8.24 bits */
220       if (val > 0xffffffUL) {
221         return 0;
222       }
223       if (parts[0] > 0xff) {
224         return 0;
225       }
226       val |= parts[0] << 24;
227       break;
228 
229     case 3:             /* a.b.c -- 8.8.16 bits */
230       if (val > 0xffff) {
231         return 0;
232       }
233       if ((parts[0] > 0xff) || (parts[1] > 0xff)) {
234         return 0;
235       }
236       val |= (parts[0] << 24) | (parts[1] << 16);
237       break;
238 
239     case 4:             /* a.b.c.d -- 8.8.8.8 bits */
240       if (val > 0xff) {
241         return 0;
242       }
243       if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff)) {
244         return 0;
245       }
246       val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
247       break;
248     default:
249       LWIP_ASSERT("unhandled", 0);
250       break;
251   }
252   if (addr) {
253     ip4_addr_set_u32(addr, lwip_htonl(val));
254   }
255   return 1;
256 }
257 
258 /**
259  * Convert numeric IP address into decimal dotted ASCII representation.
260  * returns ptr to static buffer; not reentrant!
261  *
262  * @param addr ip address in network order to convert
263  * @return pointer to a global static (!) buffer that holds the ASCII
264  *         representation of addr
265  */
266 char *
ip4addr_ntoa(const ip4_addr_t * addr)267 ip4addr_ntoa(const ip4_addr_t *addr)
268 {
269   static char str[IP4ADDR_STRLEN_MAX];
270   return ip4addr_ntoa_r(addr, str, IP4ADDR_STRLEN_MAX);
271 }
272 
273 /**
274  * Same as ip4addr_ntoa, but reentrant since a user-supplied buffer is used.
275  *
276  * @param addr ip address in network order to convert
277  * @param buf target buffer where the string is stored
278  * @param buflen length of buf
279  * @return either pointer to buf which now holds the ASCII
280  *         representation of addr or NULL if buf was too small
281  */
282 char *
ip4addr_ntoa_r(const ip4_addr_t * addr,char * buf,int buflen)283 ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen)
284 {
285   u32_t s_addr;
286   char inv[3];
287   char *rp;
288   u8_t *ap;
289   u8_t rem;
290   u8_t n;
291   u8_t i;
292   int len = 0;
293 
294   s_addr = ip4_addr_get_u32(addr);
295 
296   rp = buf;
297   ap = (u8_t *)&s_addr;
298   for (n = 0; n < 4; n++) {
299     i = 0;
300     do {
301       rem = *ap % (u8_t)10;
302       *ap /= (u8_t)10;
303       inv[i++] = (char)('0' + rem);
304     } while (*ap);
305     while (i--) {
306       if (len++ >= buflen) {
307         return NULL;
308       }
309       *rp++ = inv[i];
310     }
311     if (len++ >= buflen) {
312       return NULL;
313     }
314     *rp++ = '.';
315     ap++;
316   }
317   *--rp = 0;
318   return buf;
319 }
320 
321 #endif /* LWIP_IPV4 */
322