ip_address.anubis
2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
*** (15) IP address
An IP address is a Word32 which may be displayed numerically by the following function:
public define String
ip_addr_to_string
(
Word32 addr
) =
to_decimal(addr&255) + "." +
to_decimal((addr>>8)&255) + "." +
to_decimal((addr>>16)&255) + "." +
to_decimal((addr>>24)&255).
public define String
ip_addr_to_string
(
IpAddress ip_addr
)=
if ip_addr is ip_address(w32) then ip_addr_to_string(w32)
.
The following is used when the bytes are not in network byte order (as it is the case
in RFC 1035 DNS messages).
public define String
reverse_ip_addr_to_string
(
Word32 addr
) =
to_decimal((addr>>24)&255) + "." +
to_decimal((addr>>16)&255) + "." +
to_decimal((addr>>8)&255) + "." +
to_decimal((addr)&255).
We can also construct IP addresses with:
public define Word32
ip_address
(
(Word8,Word8,Word8,Word8) addr
) =
if addr is (b3,b2,b1,b0) then
word32(word16(b3,b2),word16(b1,b0)).
define Word32
word8_to_word32
(
Word8 x
) =
word32(word16(x,0),0).
We may also need to transform a string like "123.456.789.123" into an integer IP address.
define Bool
is_digit
(
Word8 c
) =
if c +< '0' then false else c +=< '9'.
define Maybe((Int,Word8)) // returns the next position for reading and a label.
read_label
(
String s,
Int i,
Word8 so_far
) =
if nth(i,s) is
{
failure then success((i,so_far)),
success(c) then
if c = '.'
then success((i+1,so_far))
else if is_digit(c)
then read_label(s,i+1,10*so_far+c-'0')
else failure
}.
/**
* Convert string of form 'xx.xx.xx.xx' (with 'xx' a value between 0 to 255) to an ip address
* coded on a Word32 and directly usable with Anubis network functions.
*/
public define Maybe(Word32)
ip_address
(
String s
) =
if read_label(s,0,0) is
{
failure then failure,
success(p1) then if p1 is (i2,lab1) then
if read_label(s,i2,0) is
{
failure then failure,
success(p2) then if p2 is (i3,lab2) then
if read_label(s,i3,0) is
{
failure then failure,
success(p3) then if p3 is (i4,lab3) then
if read_label(s,i4,0) is
{
failure then failure,
success(p4) then if p4 is (i4a,lab4) then
if i4a = length(s)
then success(word32(word16(lab1,lab2),word16(lab3,lab4)))
else failure
}
}
}
}.