]> git.ipfire.org Git - thirdparty/bird.git/blob - lib/ipv4.c
Merge branch 'add-path'
[thirdparty/bird.git] / lib / ipv4.c
1 /*
2 * BIRD Library -- IPv4 Address Manipulation Functions
3 *
4 * (c) 1998 Martin Mares <mj@ucw.cz>
5 *
6 * Can be freely distributed and used under the terms of the GNU GPL.
7 */
8
9 #include <stdlib.h>
10
11 #include "nest/bird.h"
12 #include "lib/ip.h"
13 #include "lib/string.h"
14
15 int
16 ipv4_classify(u32 a)
17 {
18 u32 b = a >> 24U;
19
20 if (b && b <= 0xdf)
21 {
22 if (b == 0x7f)
23 return IADDR_HOST | SCOPE_HOST;
24 else if (b == 0x0a ||
25 (a & 0xffff0000) == 0xc0a80000 ||
26 (a & 0xfff00000) == 0xac100000)
27 return IADDR_HOST | SCOPE_SITE;
28 else
29 return IADDR_HOST | SCOPE_UNIVERSE;
30 }
31 if (b >= 0xe0 && b <= 0xef)
32 return IADDR_MULTICAST | SCOPE_UNIVERSE;
33 if (a == 0xffffffff)
34 return IADDR_BROADCAST | SCOPE_LINK;
35 return IADDR_INVALID;
36 }
37
38 char *
39 ip_ntop(ip_addr a, char *b)
40 {
41 u32 x = _I(a);
42
43 return b + bsprintf(b, "%d.%d.%d.%d",
44 ((x >> 24) & 0xff),
45 ((x >> 16) & 0xff),
46 ((x >> 8) & 0xff),
47 (x & 0xff));
48 }
49
50 char *
51 ip_ntox(ip_addr a, char *b)
52 {
53 return b + bsprintf(b, "%08x", _I(a));
54 }
55
56 u32
57 ipv4_class_mask(u32 a)
58 {
59 u32 m;
60
61 if (a < 0x80000000)
62 m = 0xff000000;
63 else if (a < 0xc0000000)
64 m = 0xffff0000;
65 else
66 m = 0xffffff00;
67 while (a & ~m)
68 m |= m >> 1;
69 return m;
70 }
71
72 int
73 ip_pton(char *a, ip_addr *o)
74 {
75 int i;
76 unsigned long int l;
77 u32 ia = 0;
78
79 i=4;
80 while (i--)
81 {
82 char *d, *c = strchr(a, '.');
83 if (!c != !i)
84 return 0;
85 l = strtoul(a, &d, 10);
86 if (d != c && *d || l > 255)
87 return 0;
88 ia = (ia << 8) | l;
89 if (c)
90 c++;
91 a = c;
92 }
93 *o = ipa_from_u32(ia);
94 return 1;
95 }
96
97 byte *
98 ipv4_skip_header(byte *pkt, int *len)
99 {
100 int l = *len;
101 int q;
102
103 if (l < 20 || (*pkt & 0xf0) != 0x40)
104 return NULL;
105 q = (*pkt & 0x0f) * 4;
106 if (q > l)
107 return NULL;
108 *len -= q;
109 return pkt + q;
110 }