Debian Codegraph @

ips.go

raw
1 package utils
2
3 import (
4 "net"
5 )
6
7 // hexFieldMaxLen is the number of hex digits an IPv6 field may hold.
8 const hexFieldMaxLen = 4
9
10 // IsIPv4 reports whether s is a dotted-decimal IPv4 address. It accepts
11 // exactly what net.ParseIP accepts for the IPv4 case, without the net.IP slice,
12 // so it makes no allocations. It is the validate-only spelling of ParseIPv4,
13 // which accepts the same strings and also returns the address.
14 func IsIPv4(s string) bool {
15 _, ok := ParseIPv4(s)
16 return ok
17 }
18
19 // IsIPv6 reports whether s is an IPv6 address. It accepts exactly what
20 // net.ParseIP accepts for the IPv6 case, without the net.IP slice, so it makes
21 // no allocations. That excludes a "%zone" suffix, because net.ParseIP rejects
22 // zones.
23 //
24 // ParseIPv6 follows netip.ParseAddr instead and does accept zones, so the two
25 // disagree on zoned input by design. Callers relying on IsIPv6 to reject zones
26 // must screen '%' themselves before substituting ParseIPv6.
27 func IsIPv6(s string) bool {
28 ellipsis := -1 // position of ellipsis in ip
29
30 // Might have leading ellipsis
31 if len(s) >= 2 && s[0] == ':' && s[1] == ':' {
32 ellipsis = 0
33 s = s[2:]
34 // Might be only ellipsis
35 if len(s) == 0 {
36 return true
37 }
38 }
39
40 // Loop, parsing hex numbers followed by colon.
41 i := 0
42 for i < net.IPv6len {
43 // Hex field. Bounding the digit count is what rejects "00001":
44 // leading zeros hold the value below 0xFFFF however many of them
45 // there are, so a value-only bound lets an over-long field through.
46 // Four digits cannot exceed 0xFFFF, so no value check is needed.
47 ci := 0
48 for ; ci < len(s); ci++ {
49 c := s[ci]
50 if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
51 break
52 }
53 if ci == hexFieldMaxLen {
54 return false
55 }
56 }
57 if ci == 0 {
58 return false
59 }
60
61 if ci < len(s) && s[ci] == '.' {
62 if ellipsis < 0 && i != net.IPv6len-net.IPv4len {
63 return false
64 }
65 if i+net.IPv4len > net.IPv6len {
66 return false
67 }
68
69 if !IsIPv4(s) {
70 return false
71 }
72
73 s = ""
74 i += net.IPv4len
75 break
76 }
77
78 // Save this 16-bit chunk.
79 i += 2
80
81 // Stop at end of string.
82 s = s[ci:]
83 if len(s) == 0 {
84 break
85 }
86
87 // Otherwise must be followed by colon and more.
88 if s[0] != ':' || len(s) == 1 {
89 return false
90 }
91 s = s[1:]
92
93 // Look for ellipsis.
94 if s[0] == ':' {
95 if ellipsis >= 0 { // already have one
96 return false
97 }
98 ellipsis = i
99 s = s[1:]
100 if len(s) == 0 { // can be at end
101 break
102 }
103 }
104 }
105
106 // Must have used entire string.
107 if len(s) != 0 {
108 return false
109 }
110
111 // If didn't parse enough, expand ellipsis.
112 if i < net.IPv6len {
113 if ellipsis < 0 {
114 return false
115 }
116 } else if ellipsis >= 0 {
117 // Ellipsis must represent at least one 0 group.
118 return false
119 }
120 return true
121 }