-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathparse_ip4.go
71 lines (62 loc) · 1.97 KB
/
parse_ip4.go
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
package main
// IPv4StrToInt converts a string containing an IPv4 address to its uint32 representation.
// The input string should be in the format "xxx.xxx.xxx.xxx" where xxx is a number between 0 and 255.
// If the input string is not a valid IPv4 address, the function returns 0xFFFFFFFF.
func IPv4StrToInt(s string) uint32 {
var ip, n uint32
var r uint = 24 // r tracks the remaining bits to shift the next octet.
var dotCount byte = 1 // dotCount tracks the number of consecutive dots.
// Iterate through the input string
for i := 0; i < len(s); i++ {
switch {
case '0' <= s[i] && s[i] <= '9': // Check if the current character is a digit.
n = n*10 + uint32(s[i]-'0') // Update n with the current digit.
// Check if the current octet value exceeds the maximum allowed value (255).
if n > 0xFF {
return 0xFFFFFFFF
}
dotCount = 0 // Reset the dot count.
case s[i] == '.': // Check if the current character is a dot.
// If no more octets are expected or it's a second consecutive dot, return an error.
if r == 0 || dotCount > 0 {
return 0xFFFFFFFF
}
// Combine the current octet value with the existing IP representation.
ip |= n << r
r -= 8 // Update the remaining bits for the next octet.
n = 0 // Reset n for the next octet.
dotCount++ // Increment the dot count.
default: // If the current character is neither a digit nor a dot, return an error.
return 0xFFFFFFFF
}
}
// If the address is incomplete, return an error.
if r != 0 || dotCount > 0 {
return 0xFFFFFFFF
}
// Combine the last octet value with the existing IP representation.
ip |= n
return ip
}
func int2Ip4(ip uint32) string {
var (
b [15]byte
c int
)
for i := 24; i >= 0; i -= 8 {
d := int((ip >> i) & 0x000000FF)
for j := 100; j > 0; j /= 10 {
t := byte((d / j) + '0')
d %= j
if (t > '0') || ((c != 0) && (b[c-1] != '.')) || (j == 1) {
b[c] = t
c++
}
}
if i > 0 {
b[c] = '.'
c++
}
}
return string(b[:c])
}