netaddr.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. // Copyright 2020 The Inet.Af AUTHORS. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package netaddr contains a IP address type that's in many ways
  5. // better than the Go standard library's net.IP type. Building on that
  6. // IP type, the package also contains IPPrefix, IPPort, IPRange, and
  7. // IPSet types.
  8. //
  9. // Notably, this package's IP type takes less memory, is immutable,
  10. // comparable (supports == and being a map key), and more. See
  11. // https://github.com/inetaf/netaddr for background.
  12. //
  13. // IPv6 Zones
  14. //
  15. // IP and IPPort are the only types in this package that support IPv6
  16. // zones. Other types silently drop any passed-in zones.
  17. package netaddr // import "inet.af/netaddr"
  18. import (
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "math"
  23. "net"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "go4.org/intern"
  28. )
  29. // Sizes: (64-bit)
  30. // net.IP: 24 byte slice header + {4, 16} = 28 to 40 bytes
  31. // net.IPAddr: 40 byte slice header + {4, 16} = 44 to 56 bytes + zone length
  32. // netaddr.IP: 24 bytes (zone is per-name singleton, shared across all users)
  33. // IP represents an IPv4 or IPv6 address (with or without a scoped
  34. // addressing zone), similar to Go's net.IP or net.IPAddr.
  35. //
  36. // Unlike net.IP or net.IPAddr, the netaddr.IP is a comparable value
  37. // type (it supports == and can be a map key) and is immutable.
  38. // Its memory representation is 24 bytes on 64-bit machines (the same
  39. // size as a Go slice header) for both IPv4 and IPv6 address.
  40. type IP struct {
  41. // addr are the hi and lo bits of an IPv6 address. If z==z4,
  42. // hi and lo contain the IPv4-mapped IPv6 address.
  43. //
  44. // hi and lo are constructed by interpreting a 16-byte IPv6
  45. // address as a big-endian 128-bit number. The most significant
  46. // bits of that number go into hi, the rest into lo.
  47. //
  48. // For example, 0011:2233:4455:6677:8899:aabb:ccdd:eeff is stored as:
  49. // addr.hi = 0x0011223344556677
  50. // addr.lo = 0x8899aabbccddeeff
  51. //
  52. // We store IPs like this, rather than as [16]byte, because it
  53. // turns most operations on IPs into arithmetic and bit-twiddling
  54. // operations on 64-bit registers, which is much faster than
  55. // bytewise processing.
  56. addr uint128
  57. // z is a combination of the address family and the IPv6 zone.
  58. //
  59. // nil means invalid IP address (for the IP zero value).
  60. // z4 means an IPv4 address.
  61. // z6noz means an IPv6 address without a zone.
  62. //
  63. // Otherwise it's the interned zone name string.
  64. z *intern.Value
  65. }
  66. // z0, z4, and z6noz are sentinel IP.z values.
  67. // See the IP type's field docs.
  68. var (
  69. z0 = (*intern.Value)(nil)
  70. z4 = new(intern.Value)
  71. z6noz = new(intern.Value)
  72. )
  73. // IPv6LinkLocalAllNodes returns the IPv6 link-local all nodes multicast
  74. // address ff02::1.
  75. func IPv6LinkLocalAllNodes() IP { return IPv6Raw([16]byte{0: 0xff, 1: 0x02, 15: 0x01}) }
  76. // IPv6Unspecified returns the IPv6 unspecified address ::.
  77. func IPv6Unspecified() IP { return IP{z: z6noz} }
  78. // IPv4 returns the IP of the IPv4 address a.b.c.d.
  79. func IPv4(a, b, c, d uint8) IP {
  80. return IP{
  81. addr: uint128{0, 0xffff00000000 | uint64(a)<<24 | uint64(b)<<16 | uint64(c)<<8 | uint64(d)},
  82. z: z4,
  83. }
  84. }
  85. // IPv6Raw returns the IPv6 address given by the bytes in addr,
  86. // without an implicit Unmap call to unmap any v6-mapped IPv4
  87. // address.
  88. func IPv6Raw(addr [16]byte) IP {
  89. return IP{
  90. addr: uint128{
  91. binary.BigEndian.Uint64(addr[:8]),
  92. binary.BigEndian.Uint64(addr[8:]),
  93. },
  94. z: z6noz,
  95. }
  96. }
  97. // ipv6Slice is like IPv6Raw, but operates on a 16-byte slice. Assumes
  98. // slice is 16 bytes, caller must enforce this.
  99. func ipv6Slice(addr []byte) IP {
  100. return IP{
  101. addr: uint128{
  102. binary.BigEndian.Uint64(addr[:8]),
  103. binary.BigEndian.Uint64(addr[8:]),
  104. },
  105. z: z6noz,
  106. }
  107. }
  108. // IPFrom16 returns the IP address given by the bytes in addr,
  109. // unmapping any v6-mapped IPv4 address.
  110. //
  111. // It is equivalent to calling IPv6Raw(addr).Unmap().
  112. func IPFrom16(addr [16]byte) IP {
  113. return IPv6Raw(addr).Unmap()
  114. }
  115. // IPFrom4 returns the IPv4 address given by the bytes in addr.
  116. // It is equivalent to calling IPv4(addr[0], addr[1], addr[2], addr[3]).
  117. func IPFrom4(addr [4]byte) IP {
  118. return IPv4(addr[0], addr[1], addr[2], addr[3])
  119. }
  120. // ParseIP parses s as an IP address, returning the result. The string
  121. // s can be in dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"),
  122. // or IPv6 with a scoped addressing zone ("fe80::1cc0:3e8c:119f:c2e1%ens18").
  123. func ParseIP(s string) (IP, error) {
  124. for i := 0; i < len(s); i++ {
  125. switch s[i] {
  126. case '.':
  127. return parseIPv4(s)
  128. case ':':
  129. return parseIPv6(s)
  130. case '%':
  131. // Assume that this was trying to be an IPv6 address with
  132. // a zone specifier, but the address is missing.
  133. return IP{}, parseIPError{in: s, msg: "missing IPv6 address"}
  134. }
  135. }
  136. return IP{}, parseIPError{in: s, msg: "unable to parse IP"}
  137. }
  138. // MustParseIP calls ParseIP(s) and panics on error.
  139. // It is intended for use in tests with hard-coded strings.
  140. func MustParseIP(s string) IP {
  141. ip, err := ParseIP(s)
  142. if err != nil {
  143. panic(err)
  144. }
  145. return ip
  146. }
  147. type parseIPError struct {
  148. in string // the string given to ParseIP
  149. msg string // an explanation of the parse failure
  150. at string // optionally, the unparsed portion of in at which the error occurred.
  151. }
  152. func (err parseIPError) Error() string {
  153. if err.at != "" {
  154. return fmt.Sprintf("ParseIP(%q): %s (at %q)", err.in, err.msg, err.at)
  155. }
  156. return fmt.Sprintf("ParseIP(%q): %s", err.in, err.msg)
  157. }
  158. // parseIPv4 parses s as an IPv4 address (in form "192.168.0.1").
  159. func parseIPv4(s string) (ip IP, err error) {
  160. var fields [3]uint8
  161. var val, pos int
  162. for i := 0; i < len(s); i++ {
  163. if s[i] >= '0' && s[i] <= '9' {
  164. val = val*10 + int(s[i]) - '0'
  165. if val > 255 {
  166. return IP{}, parseIPError{in: s, msg: "IPv4 field has value >255"}
  167. }
  168. } else if s[i] == '.' {
  169. // .1.2.3
  170. // 1.2.3.
  171. // 1..2.3
  172. if i == 0 || i == len(s)-1 || s[i-1] == '.' {
  173. return IP{}, parseIPError{in: s, msg: "IPv4 field must have at least one digit", at: s[i:]}
  174. }
  175. // 1.2.3.4.5
  176. if pos == 3 {
  177. return IP{}, parseIPError{in: s, msg: "IPv4 address too long"}
  178. }
  179. fields[pos] = uint8(val)
  180. pos++
  181. val = 0
  182. } else {
  183. return IP{}, parseIPError{in: s, msg: "unexpected character", at: s[i:]}
  184. }
  185. }
  186. if pos < 3 {
  187. return IP{}, parseIPError{in: s, msg: "IPv4 address too short"}
  188. }
  189. return IPv4(fields[0], fields[1], fields[2], uint8(val)), nil
  190. }
  191. // parseIPv6 parses s as an IPv6 address (in form "2001:db8::68").
  192. func parseIPv6(in string) (IP, error) {
  193. s := in
  194. // Split off the zone right from the start. Yes it's a second scan
  195. // of the string, but trying to handle it inline makes a bunch of
  196. // other inner loop conditionals more expensive, and it ends up
  197. // being slower.
  198. zone := ""
  199. i := strings.IndexByte(s, '%')
  200. if i != -1 {
  201. s, zone = s[:i], s[i+1:]
  202. if zone == "" {
  203. // Not allowed to have an empty zone if explicitly specified.
  204. return IP{}, parseIPError{in: in, msg: "zone must be a non-empty string"}
  205. }
  206. }
  207. var ip [16]byte
  208. ellipsis := -1 // position of ellipsis in ip
  209. // Might have leading ellipsis
  210. if len(s) >= 2 && s[0] == ':' && s[1] == ':' {
  211. ellipsis = 0
  212. s = s[2:]
  213. // Might be only ellipsis
  214. if len(s) == 0 {
  215. return IPv6Unspecified().WithZone(zone), nil
  216. }
  217. }
  218. // Loop, parsing hex numbers followed by colon.
  219. i = 0
  220. for i < 16 {
  221. // Hex number. Similar to parseIPv4, inlining the hex number
  222. // parsing yields a significant performance increase.
  223. off := 0
  224. acc := uint32(0)
  225. for ; off < len(s); off++ {
  226. c := s[off]
  227. if c >= '0' && c <= '9' {
  228. acc = (acc << 4) + uint32(c-'0')
  229. } else if c >= 'a' && c <= 'f' {
  230. acc = (acc << 4) + uint32(c-'a'+10)
  231. } else if c >= 'A' && c <= 'F' {
  232. acc = (acc << 4) + uint32(c-'A'+10)
  233. } else {
  234. break
  235. }
  236. if acc > math.MaxUint16 {
  237. // Overflow, fail.
  238. return IP{}, parseIPError{in: in, msg: "IPv6 field has value >=2^16", at: s}
  239. }
  240. }
  241. if off == 0 {
  242. // No digits found, fail.
  243. return IP{}, parseIPError{in: in, msg: "each colon-separated field must have at least one digit", at: s}
  244. }
  245. // If followed by dot, might be in trailing IPv4.
  246. if off < len(s) && s[off] == '.' {
  247. if ellipsis < 0 && i != 12 {
  248. // Not the right place.
  249. return IP{}, parseIPError{in: in, msg: "embedded IPv4 address must replace the final 2 fields of the address", at: s}
  250. }
  251. if i+4 > 16 {
  252. // Not enough room.
  253. return IP{}, parseIPError{in: in, msg: "too many hex fields to fit an embedded IPv4 at the end of the address", at: s}
  254. }
  255. // TODO: could make this a bit faster by having a helper
  256. // that parses to a [4]byte, and have both parseIPv4 and
  257. // parseIPv6 use it.
  258. ip4, err := parseIPv4(s)
  259. if err != nil {
  260. return IP{}, parseIPError{in: in, msg: err.Error(), at: s}
  261. }
  262. ip[i] = ip4.v4(0)
  263. ip[i+1] = ip4.v4(1)
  264. ip[i+2] = ip4.v4(2)
  265. ip[i+3] = ip4.v4(3)
  266. s = ""
  267. i += 4
  268. break
  269. }
  270. // Save this 16-bit chunk.
  271. ip[i] = byte(acc >> 8)
  272. ip[i+1] = byte(acc)
  273. i += 2
  274. // Stop at end of string.
  275. s = s[off:]
  276. if len(s) == 0 {
  277. break
  278. }
  279. // Otherwise must be followed by colon and more.
  280. if s[0] != ':' {
  281. return IP{}, parseIPError{in: in, msg: "unexpected character, want colon", at: s}
  282. } else if len(s) == 1 {
  283. return IP{}, parseIPError{in: in, msg: "colon must be followed by more characters", at: s}
  284. }
  285. s = s[1:]
  286. // Look for ellipsis.
  287. if s[0] == ':' {
  288. if ellipsis >= 0 { // already have one
  289. return IP{}, parseIPError{in: in, msg: "multiple :: in address", at: s}
  290. }
  291. ellipsis = i
  292. s = s[1:]
  293. if len(s) == 0 { // can be at end
  294. break
  295. }
  296. }
  297. }
  298. // Must have used entire string.
  299. if len(s) != 0 {
  300. return IP{}, parseIPError{in: in, msg: "trailing garbage after address", at: s}
  301. }
  302. // If didn't parse enough, expand ellipsis.
  303. if i < 16 {
  304. if ellipsis < 0 {
  305. return IP{}, parseIPError{in: in, msg: "address string too short"}
  306. }
  307. n := 16 - i
  308. for j := i - 1; j >= ellipsis; j-- {
  309. ip[j+n] = ip[j]
  310. }
  311. for j := ellipsis + n - 1; j >= ellipsis; j-- {
  312. ip[j] = 0
  313. }
  314. } else if ellipsis >= 0 {
  315. // Ellipsis must represent at least one 0 group.
  316. return IP{}, parseIPError{in: in, msg: "the :: must expand to at least one field of zeros"}
  317. }
  318. return IPv6Raw(ip).WithZone(zone), nil
  319. }
  320. // FromStdIP returns an IP from the standard library's IP type.
  321. //
  322. // If std is invalid, ok is false.
  323. //
  324. // FromStdIP implicitly unmaps IPv6-mapped IPv4 addresses. That is, if
  325. // len(std) == 16 and contains an IPv4 address, only the IPv4 part is
  326. // returned, without the IPv6 wrapper. This is the common form returned by
  327. // the standard library's ParseIP: https://play.golang.org/p/qdjylUkKWxl.
  328. // To convert a standard library IP without the implicit unmapping, use
  329. // FromStdIPRaw.
  330. func FromStdIP(std net.IP) (ip IP, ok bool) {
  331. ret, ok := FromStdIPRaw(std)
  332. if ret.Is4in6() {
  333. ret.z = z4
  334. }
  335. return ret, ok
  336. }
  337. // FromStdIPRaw returns an IP from the standard library's IP type.
  338. // If std is invalid, ok is false.
  339. // Unlike FromStdIP, FromStdIPRaw does not do an implicit Unmap if
  340. // len(std) == 16 and contains an IPv6-mapped IPv4 address.
  341. func FromStdIPRaw(std net.IP) (ip IP, ok bool) {
  342. switch len(std) {
  343. case 4:
  344. return IPv4(std[0], std[1], std[2], std[3]), true
  345. case 16:
  346. return ipv6Slice(std), true
  347. }
  348. return IP{}, false
  349. }
  350. // v4 returns the i'th byte of ip. If ip is not an IPv4, v4 returns
  351. // unspecified garbage.
  352. func (ip IP) v4(i uint8) uint8 {
  353. return uint8(ip.addr.lo >> ((3 - i) * 8))
  354. }
  355. // v6 returns the i'th byte of ip. If ip is an IPv4 address, this
  356. // accesses the IPv4-mapped IPv6 address form of the IP.
  357. func (ip IP) v6(i uint8) uint8 {
  358. return uint8(*(ip.addr.halves()[(i/8)%2]) >> ((7 - i%8) * 8))
  359. }
  360. // v6u16 returns the i'th 16-bit word of ip. If ip is an IPv4 address,
  361. // this accesses the IPv4-mapped IPv6 address form of the IP.
  362. func (ip IP) v6u16(i uint8) uint16 {
  363. return uint16(*(ip.addr.halves()[(i/4)%2]) >> ((3 - i%4) * 16))
  364. }
  365. // IsZero reports whether ip is the zero value of the IP type.
  366. // The zero value is not a valid IP address of any type.
  367. //
  368. // Note that "0.0.0.0" and "::" are not the zero value. Use IsUnspecified to
  369. // check for these values instead.
  370. func (ip IP) IsZero() bool {
  371. // Faster than comparing ip == IP{}, but effectively equivalent,
  372. // as there's no way to make an IP with a nil z from this package.
  373. return ip.z == z0
  374. }
  375. // IsValid whether the IP is an initialized value and not the IP
  376. // type's zero value.
  377. //
  378. // Note that both "0.0.0.0" and "::" are valid, non-zero values.
  379. func (ip IP) IsValid() bool { return ip.z != z0 }
  380. // BitLen returns the number of bits in the IP address:
  381. // 32 for IPv4 or 128 for IPv6.
  382. // For the zero value (see IP.IsZero), it returns 0.
  383. // For IP4-mapped IPv6 addresses, it returns 128.
  384. func (ip IP) BitLen() uint8 {
  385. switch ip.z {
  386. case z0:
  387. return 0
  388. case z4:
  389. return 32
  390. }
  391. return 128
  392. }
  393. // Zone returns ip's IPv6 scoped addressing zone, if any.
  394. func (ip IP) Zone() string {
  395. if ip.z == nil {
  396. return ""
  397. }
  398. zone, _ := ip.z.Get().(string)
  399. return zone
  400. }
  401. // Compare returns an integer comparing two IPs.
  402. // The result will be 0 if ip==ip2, -1 if ip < ip2, and +1 if ip > ip2.
  403. // The definition of "less than" is the same as the IP.Less method.
  404. func (ip IP) Compare(ip2 IP) int {
  405. f1, f2 := ip.BitLen(), ip2.BitLen()
  406. if f1 < f2 {
  407. return -1
  408. }
  409. if f1 > f2 {
  410. return 1
  411. }
  412. if hi1, hi2 := ip.addr.hi, ip2.addr.hi; hi1 < hi2 {
  413. return -1
  414. } else if hi1 > hi2 {
  415. return 1
  416. }
  417. if lo1, lo2 := ip.addr.lo, ip2.addr.lo; lo1 < lo2 {
  418. return -1
  419. } else if lo1 > lo2 {
  420. return 1
  421. }
  422. if ip.Is6() {
  423. za, zb := ip.Zone(), ip2.Zone()
  424. if za < zb {
  425. return -1
  426. } else if za > zb {
  427. return 1
  428. }
  429. }
  430. return 0
  431. }
  432. // Less reports whether ip sorts before ip2.
  433. // IP addresses sort first by length, then their address.
  434. // IPv6 addresses with zones sort just after the same address without a zone.
  435. func (ip IP) Less(ip2 IP) bool { return ip.Compare(ip2) == -1 }
  436. func (ip IP) lessOrEq(ip2 IP) bool { return ip.Compare(ip2) <= 0 }
  437. // ipZone returns the standard library net.IP from ip, as well
  438. // as the zone.
  439. // The optional reuse IP provides memory to reuse.
  440. func (ip IP) ipZone(reuse net.IP) (stdIP net.IP, zone string) {
  441. base := reuse[:0]
  442. switch {
  443. case ip.z == z0:
  444. return nil, ""
  445. case ip.Is4():
  446. a4 := ip.As4()
  447. return append(base, a4[:]...), ""
  448. default:
  449. a16 := ip.As16()
  450. return append(base, a16[:]...), ip.Zone()
  451. }
  452. }
  453. // IPAddr returns the net.IPAddr representation of an IP. The returned value is
  454. // always non-nil, but the IPAddr.IP will be nil if ip is the zero value.
  455. // If ip contains a zone identifier, IPAddr.Zone is populated.
  456. func (ip IP) IPAddr() *net.IPAddr {
  457. stdIP, zone := ip.ipZone(nil)
  458. return &net.IPAddr{IP: stdIP, Zone: zone}
  459. }
  460. // Is4 reports whether ip is an IPv4 address.
  461. //
  462. // It returns false for IP4-mapped IPv6 addresses. See IP.Unmap.
  463. func (ip IP) Is4() bool {
  464. return ip.z == z4
  465. }
  466. // Is4in6 reports whether ip is an IPv4-mapped IPv6 address.
  467. func (ip IP) Is4in6() bool {
  468. return ip.Is6() && ip.addr.hi == 0 && ip.addr.lo>>32 == 0xffff
  469. }
  470. // Is6 reports whether ip is an IPv6 address, including IPv4-mapped
  471. // IPv6 addresses.
  472. func (ip IP) Is6() bool {
  473. return ip.z != z0 && ip.z != z4
  474. }
  475. // Unmap returns ip with any IPv4-mapped IPv6 address prefix removed.
  476. //
  477. // That is, if ip is an IPv6 address wrapping an IPv4 adddress, it
  478. // returns the wrapped IPv4 address. Otherwise it returns ip, regardless
  479. // of its type.
  480. func (ip IP) Unmap() IP {
  481. if ip.Is4in6() {
  482. ip.z = z4
  483. }
  484. return ip
  485. }
  486. // WithZone returns an IP that's the same as ip but with the provided
  487. // zone. If zone is empty, the zone is removed. If ip is an IPv4
  488. // address it's returned unchanged.
  489. func (ip IP) WithZone(zone string) IP {
  490. if !ip.Is6() {
  491. return ip
  492. }
  493. if zone == "" {
  494. ip.z = z6noz
  495. return ip
  496. }
  497. ip.z = intern.GetByString(zone)
  498. return ip
  499. }
  500. // noZone unconditionally strips the zone from IP.
  501. // It's similar to WithZone, but small enough to be inlinable.
  502. func (ip IP) withoutZone() IP {
  503. if !ip.Is6() {
  504. return ip
  505. }
  506. ip.z = z6noz
  507. return ip
  508. }
  509. // hasZone reports whether IP has an IPv6 zone.
  510. func (ip IP) hasZone() bool {
  511. return ip.z != z0 && ip.z != z4 && ip.z != z6noz
  512. }
  513. // IsLinkLocalUnicast reports whether ip is a link-local unicast address.
  514. // If ip is the zero value, it will return false.
  515. func (ip IP) IsLinkLocalUnicast() bool {
  516. // Dynamic Configuration of IPv4 Link-Local Addresses
  517. // https://datatracker.ietf.org/doc/html/rfc3927#section-2.1
  518. if ip.Is4() {
  519. return ip.v4(0) == 169 && ip.v4(1) == 254
  520. }
  521. // IP Version 6 Addressing Architecture (2.4 Address Type Identification)
  522. // https://datatracker.ietf.org/doc/html/rfc4291#section-2.4
  523. if ip.Is6() {
  524. return ip.v6u16(0)&0xffc0 == 0xfe80
  525. }
  526. return false // zero value
  527. }
  528. // IsLoopback reports whether ip is a loopback address. If ip is the zero value,
  529. // it will return false.
  530. func (ip IP) IsLoopback() bool {
  531. // Requirements for Internet Hosts -- Communication Layers (3.2.1.3 Addressing)
  532. // https://datatracker.ietf.org/doc/html/rfc1122#section-3.2.1.3
  533. if ip.Is4() {
  534. return ip.v4(0) == 127
  535. }
  536. // IP Version 6 Addressing Architecture (2.4 Address Type Identification)
  537. // https://datatracker.ietf.org/doc/html/rfc4291#section-2.4
  538. if ip.Is6() {
  539. return ip.addr.hi == 0 && ip.addr.lo == 1
  540. }
  541. return false // zero value
  542. }
  543. // IsMulticast reports whether ip is a multicast address. If ip is the zero
  544. // value, it will return false.
  545. func (ip IP) IsMulticast() bool {
  546. // Host Extensions for IP Multicasting (4. HOST GROUP ADDRESSES)
  547. // https://datatracker.ietf.org/doc/html/rfc1112#section-4
  548. if ip.Is4() {
  549. return ip.v4(0)&0xf0 == 0xe0
  550. }
  551. // IP Version 6 Addressing Architecture (2.4 Address Type Identification)
  552. // https://datatracker.ietf.org/doc/html/rfc4291#section-2.4
  553. if ip.Is6() {
  554. return ip.addr.hi>>(64-8) == 0xff // ip.v6(0) == 0xff
  555. }
  556. return false // zero value
  557. }
  558. // IsInterfaceLocalMulticast reports whether ip is an IPv6 interface-local
  559. // multicast address. If ip is the zero value or an IPv4 address, it will return
  560. // false.
  561. func (ip IP) IsInterfaceLocalMulticast() bool {
  562. // IPv6 Addressing Architecture (2.7.1. Pre-Defined Multicast Addresses)
  563. // https://datatracker.ietf.org/doc/html/rfc4291#section-2.7.1
  564. if ip.Is6() {
  565. return ip.v6u16(0)&0xff0f == 0xff01
  566. }
  567. return false // zero value
  568. }
  569. // IsLinkLocalMulticast reports whether ip is a link-local multicast address.
  570. // If ip is the zero value, it will return false.
  571. func (ip IP) IsLinkLocalMulticast() bool {
  572. // IPv4 Multicast Guidelines (4. Local Network Control Block (224.0.0/24))
  573. // https://datatracker.ietf.org/doc/html/rfc5771#section-4
  574. if ip.Is4() {
  575. return ip.v4(0) == 224 && ip.v4(1) == 0 && ip.v4(2) == 0
  576. }
  577. // IPv6 Addressing Architecture (2.7.1. Pre-Defined Multicast Addresses)
  578. // https://datatracker.ietf.org/doc/html/rfc4291#section-2.7.1
  579. if ip.Is6() {
  580. return ip.v6u16(0)&0xff0f == 0xff02
  581. }
  582. return false // zero value
  583. }
  584. // IsGlobalUnicast reports whether ip is a global unicast address.
  585. //
  586. // It returns true for IPv6 addresses which fall outside of the current
  587. // IANA-allocated 2000::/3 global unicast space, with the exception of the
  588. // link-local address space. It also returns true even if ip is in the IPv4
  589. // private address space or IPv6 unique local address space. If ip is the zero
  590. // value, it will return false.
  591. //
  592. // For reference, see RFC 1122, RFC 4291, and RFC 4632.
  593. func (ip IP) IsGlobalUnicast() bool {
  594. if ip.z == z0 {
  595. // Invalid or zero-value.
  596. return false
  597. }
  598. // Match the stdlib's IsGlobalUnicast logic. Notably private IPv4 addresses
  599. // and ULA IPv6 addresses are still considered "global unicast".
  600. if ip.Is4() && (ip == IPv4(0, 0, 0, 0) || ip == IPv4(255, 255, 255, 255)) {
  601. return false
  602. }
  603. return ip != IPv6Unspecified() &&
  604. !ip.IsLoopback() &&
  605. !ip.IsMulticast() &&
  606. !ip.IsLinkLocalUnicast()
  607. }
  608. // IsPrivate reports whether ip is a private address, according to RFC 1918
  609. // (IPv4 addresses) and RFC 4193 (IPv6 addresses). That is, it reports whether
  610. // ip is in 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, or fc00::/7. This is the
  611. // same as the standard library's net.IP.IsPrivate.
  612. func (ip IP) IsPrivate() bool {
  613. // Match the stdlib's IsPrivate logic.
  614. if ip.Is4() {
  615. // RFC 1918 allocates 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16 as
  616. // private IPv4 address subnets.
  617. return ip.v4(0) == 10 ||
  618. (ip.v4(0) == 172 && ip.v4(1)&0xf0 == 16) ||
  619. (ip.v4(0) == 192 && ip.v4(1) == 168)
  620. }
  621. if ip.Is6() {
  622. // RFC 4193 allocates fc00::/7 as the unique local unicast IPv6 address
  623. // subnet.
  624. return ip.v6(0)&0xfe == 0xfc
  625. }
  626. return false // zero value
  627. }
  628. // IsUnspecified reports whether ip is an unspecified address, either the IPv4
  629. // address "0.0.0.0" or the IPv6 address "::".
  630. //
  631. // Note that the IP zero value is not an unspecified address. Use IsZero to
  632. // check for the zero value instead.
  633. func (ip IP) IsUnspecified() bool {
  634. return ip == IPv4(0, 0, 0, 0) || ip == IPv6Unspecified()
  635. }
  636. // Prefix applies a CIDR mask of leading bits to IP, producing an IPPrefix
  637. // of the specified length. If IP is the zero value, a zero-value IPPrefix and
  638. // a nil error are returned. If bits is larger than 32 for an IPv4 address or
  639. // 128 for an IPv6 address, an error is returned.
  640. func (ip IP) Prefix(bits uint8) (IPPrefix, error) {
  641. effectiveBits := bits
  642. switch ip.z {
  643. case z0:
  644. return IPPrefix{}, nil
  645. case z4:
  646. if bits > 32 {
  647. return IPPrefix{}, fmt.Errorf("prefix length %d too large for IPv4", bits)
  648. }
  649. effectiveBits += 96
  650. default:
  651. if bits > 128 {
  652. return IPPrefix{}, fmt.Errorf("prefix length %d too large for IPv6", bits)
  653. }
  654. }
  655. ip.addr = ip.addr.and(mask6[effectiveBits])
  656. return IPPrefixFrom(ip, bits), nil
  657. }
  658. // Netmask applies a bit mask to IP, producing an IPPrefix. If IP is the
  659. // zero value, a zero-value IPPrefix and a nil error are returned. If the
  660. // netmask length is not 4 for IPv4 or 16 for IPv6, an error is
  661. // returned. If the netmask is non-contiguous, an error is returned.
  662. func (ip IP) Netmask(mask []byte) (IPPrefix, error) {
  663. l := len(mask)
  664. switch ip.z {
  665. case z0:
  666. return IPPrefix{}, nil
  667. case z4:
  668. if l != net.IPv4len {
  669. return IPPrefix{}, fmt.Errorf("netmask length %d incorrect for IPv4", l)
  670. }
  671. default:
  672. if l != net.IPv6len {
  673. return IPPrefix{}, fmt.Errorf("netmask length %d incorrect for IPv6", l)
  674. }
  675. }
  676. ones, bits := net.IPMask(mask).Size()
  677. if ones == 0 && bits == 0 {
  678. return IPPrefix{}, errors.New("netmask is non-contiguous")
  679. }
  680. return ip.Prefix(uint8(ones))
  681. }
  682. // As16 returns the IP address in its 16 byte representation.
  683. // IPv4 addresses are returned in their v6-mapped form.
  684. // IPv6 addresses with zones are returned without their zone (use the
  685. // Zone method to get it).
  686. // The ip zero value returns all zeroes.
  687. func (ip IP) As16() [16]byte {
  688. var ret [16]byte
  689. binary.BigEndian.PutUint64(ret[:8], ip.addr.hi)
  690. binary.BigEndian.PutUint64(ret[8:], ip.addr.lo)
  691. return ret
  692. }
  693. // As4 returns an IPv4 or IPv4-in-IPv6 address in its 4 byte representation.
  694. // If ip is the IP zero value or an IPv6 address, As4 panics.
  695. // Note that 0.0.0.0 is not the zero value.
  696. func (ip IP) As4() [4]byte {
  697. if ip.z == z4 || ip.Is4in6() {
  698. var ret [4]byte
  699. binary.BigEndian.PutUint32(ret[:], uint32(ip.addr.lo))
  700. return ret
  701. }
  702. if ip.z == z0 {
  703. panic("As4 called on IP zero value")
  704. }
  705. panic("As4 called on IPv6 address")
  706. }
  707. // Next returns the IP following ip.
  708. // If there is none, it returns the IP zero value.
  709. func (ip IP) Next() IP {
  710. ip.addr = ip.addr.addOne()
  711. if ip.Is4() {
  712. if uint32(ip.addr.lo) == 0 {
  713. // Overflowed.
  714. return IP{}
  715. }
  716. } else {
  717. if ip.addr.isZero() {
  718. // Overflowed
  719. return IP{}
  720. }
  721. }
  722. return ip
  723. }
  724. // Prior returns the IP before ip.
  725. // If there is none, it returns the IP zero value.
  726. func (ip IP) Prior() IP {
  727. if ip.Is4() {
  728. if uint32(ip.addr.lo) == 0 {
  729. return IP{}
  730. }
  731. } else if ip.addr.isZero() {
  732. return IP{}
  733. }
  734. ip.addr = ip.addr.subOne()
  735. return ip
  736. }
  737. // String returns the string form of the IP address ip.
  738. // It returns one of 4 forms:
  739. //
  740. // - "invalid IP", if ip is the zero value
  741. // - IPv4 dotted decimal ("192.0.2.1")
  742. // - IPv6 ("2001:db8::1")
  743. // - IPv6 with zone ("fe80:db8::1%eth0")
  744. //
  745. // Note that unlike the Go standard library's IP.String method,
  746. // IP4-mapped IPv6 addresses do not format as dotted decimals.
  747. func (ip IP) String() string {
  748. switch ip.z {
  749. case z0:
  750. return "zero IP"
  751. case z4:
  752. return ip.string4()
  753. default:
  754. return ip.string6()
  755. }
  756. }
  757. // AppendTo appends a text encoding of ip,
  758. // as generated by MarshalText,
  759. // to b and returns the extended buffer.
  760. func (ip IP) AppendTo(b []byte) []byte {
  761. switch ip.z {
  762. case z0:
  763. return b
  764. case z4:
  765. return ip.appendTo4(b)
  766. default:
  767. return ip.appendTo6(b)
  768. }
  769. }
  770. // digits is a string of the hex digits from 0 to f. It's used in
  771. // appendDecimal and appendHex to format IP addresses.
  772. const digits = "0123456789abcdef"
  773. // appendDecimal appends the decimal string representation of x to b.
  774. func appendDecimal(b []byte, x uint8) []byte {
  775. // Using this function rather than strconv.AppendUint makes IPv4
  776. // string building 2x faster.
  777. if x >= 100 {
  778. b = append(b, digits[x/100])
  779. }
  780. if x >= 10 {
  781. b = append(b, digits[x/10%10])
  782. }
  783. return append(b, digits[x%10])
  784. }
  785. // appendHex appends the hex string representation of x to b.
  786. func appendHex(b []byte, x uint16) []byte {
  787. // Using this function rather than strconv.AppendUint makes IPv6
  788. // string building 2x faster.
  789. if x >= 0x1000 {
  790. b = append(b, digits[x>>12])
  791. }
  792. if x >= 0x100 {
  793. b = append(b, digits[x>>8&0xf])
  794. }
  795. if x >= 0x10 {
  796. b = append(b, digits[x>>4&0xf])
  797. }
  798. return append(b, digits[x&0xf])
  799. }
  800. // appendHexPad appends the fully padded hex string representation of x to b.
  801. func appendHexPad(b []byte, x uint16) []byte {
  802. return append(b, digits[x>>12], digits[x>>8&0xf], digits[x>>4&0xf], digits[x&0xf])
  803. }
  804. func (ip IP) string4() string {
  805. const max = len("255.255.255.255")
  806. ret := make([]byte, 0, max)
  807. ret = ip.appendTo4(ret)
  808. return string(ret)
  809. }
  810. func (ip IP) appendTo4(ret []byte) []byte {
  811. ret = appendDecimal(ret, ip.v4(0))
  812. ret = append(ret, '.')
  813. ret = appendDecimal(ret, ip.v4(1))
  814. ret = append(ret, '.')
  815. ret = appendDecimal(ret, ip.v4(2))
  816. ret = append(ret, '.')
  817. ret = appendDecimal(ret, ip.v4(3))
  818. return ret
  819. }
  820. // string6 formats ip in IPv6 textual representation. It follows the
  821. // guidelines in section 4 of RFC 5952
  822. // (https://tools.ietf.org/html/rfc5952#section-4): no unnecessary
  823. // zeros, use :: to elide the longest run of zeros, and don't use ::
  824. // to compact a single zero field.
  825. func (ip IP) string6() string {
  826. // Use a zone with a "plausibly long" name, so that most zone-ful
  827. // IP addresses won't require additional allocation.
  828. //
  829. // The compiler does a cool optimization here, where ret ends up
  830. // stack-allocated and so the only allocation this function does
  831. // is to construct the returned string. As such, it's okay to be a
  832. // bit greedy here, size-wise.
  833. const max = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%enp5s0")
  834. ret := make([]byte, 0, max)
  835. ret = ip.appendTo6(ret)
  836. return string(ret)
  837. }
  838. func (ip IP) appendTo6(ret []byte) []byte {
  839. zeroStart, zeroEnd := uint8(255), uint8(255)
  840. for i := uint8(0); i < 8; i++ {
  841. j := i
  842. for j < 8 && ip.v6u16(j) == 0 {
  843. j++
  844. }
  845. if l := j - i; l >= 2 && l > zeroEnd-zeroStart {
  846. zeroStart, zeroEnd = i, j
  847. }
  848. }
  849. for i := uint8(0); i < 8; i++ {
  850. if i == zeroStart {
  851. ret = append(ret, ':', ':')
  852. i = zeroEnd
  853. if i >= 8 {
  854. break
  855. }
  856. } else if i > 0 {
  857. ret = append(ret, ':')
  858. }
  859. ret = appendHex(ret, ip.v6u16(i))
  860. }
  861. if ip.z != z6noz {
  862. ret = append(ret, '%')
  863. ret = append(ret, ip.Zone()...)
  864. }
  865. return ret
  866. }
  867. // StringExpanded is like String but IPv6 addresses are expanded with leading
  868. // zeroes and no "::" compression. For example, "2001:db8::1" becomes
  869. // "2001:0db8:0000:0000:0000:0000:0000:0001".
  870. func (ip IP) StringExpanded() string {
  871. switch ip.z {
  872. case z0, z4:
  873. return ip.String()
  874. }
  875. const size = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
  876. ret := make([]byte, 0, size)
  877. for i := uint8(0); i < 8; i++ {
  878. if i > 0 {
  879. ret = append(ret, ':')
  880. }
  881. ret = appendHexPad(ret, ip.v6u16(i))
  882. }
  883. if ip.z != z6noz {
  884. // The addition of a zone will cause a second allocation, but when there
  885. // is no zone the ret slice will be stack allocated.
  886. ret = append(ret, '%')
  887. ret = append(ret, ip.Zone()...)
  888. }
  889. return string(ret)
  890. }
  891. // MarshalText implements the encoding.TextMarshaler interface,
  892. // The encoding is the same as returned by String, with one exception:
  893. // If ip is the zero value, the encoding is the empty string.
  894. func (ip IP) MarshalText() ([]byte, error) {
  895. switch ip.z {
  896. case z0:
  897. return []byte(""), nil
  898. case z4:
  899. max := len("255.255.255.255")
  900. b := make([]byte, 0, max)
  901. return ip.appendTo4(b), nil
  902. default:
  903. max := len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%enp5s0")
  904. b := make([]byte, 0, max)
  905. return ip.appendTo6(b), nil
  906. }
  907. }
  908. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  909. // The IP address is expected in a form accepted by ParseIP.
  910. // It returns an error if *ip is not the IP zero value.
  911. func (ip *IP) UnmarshalText(text []byte) error {
  912. if ip.z != z0 {
  913. return errors.New("refusing to Unmarshal into non-zero IP")
  914. }
  915. if len(text) == 0 {
  916. return nil
  917. }
  918. var err error
  919. *ip, err = ParseIP(string(text))
  920. return err
  921. }
  922. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  923. func (ip IP) MarshalBinary() ([]byte, error) {
  924. switch ip.z {
  925. case z0:
  926. return nil, nil
  927. case z4:
  928. b := ip.As4()
  929. return b[:], nil
  930. default:
  931. b16 := ip.As16()
  932. b := b16[:]
  933. if z := ip.Zone(); z != "" {
  934. b = append(b, []byte(z)...)
  935. }
  936. return b, nil
  937. }
  938. }
  939. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  940. func (ip *IP) UnmarshalBinary(b []byte) error {
  941. if ip.z != z0 {
  942. return errors.New("refusing to Unmarshal into non-zero IP")
  943. }
  944. n := len(b)
  945. switch {
  946. case n == 0:
  947. return nil
  948. case n == 4:
  949. *ip = IPv4(b[0], b[1], b[2], b[3])
  950. return nil
  951. case n == 16:
  952. *ip = ipv6Slice(b)
  953. return nil
  954. case n > 16:
  955. *ip = ipv6Slice(b[:16]).WithZone(string(b[16:]))
  956. return nil
  957. }
  958. return fmt.Errorf("unexpected ip size: %v", len(b))
  959. }
  960. // IPPort is an IP and a port number.
  961. type IPPort struct {
  962. ip IP
  963. port uint16
  964. }
  965. // IPPortFrom returns an IPPort with IP ip and port port.
  966. // It does not allocate.
  967. func IPPortFrom(ip IP, port uint16) IPPort { return IPPort{ip: ip, port: port} }
  968. // WithIP returns an IPPort with IP ip and port p.Port().
  969. func (p IPPort) WithIP(ip IP) IPPort { return IPPort{ip: ip, port: p.port} }
  970. // WithIP returns an IPPort with IP p.IP() and port port.
  971. func (p IPPort) WithPort(port uint16) IPPort { return IPPort{ip: p.ip, port: port} }
  972. // IP returns p's IP.
  973. func (p IPPort) IP() IP { return p.ip }
  974. // Port returns p's port.
  975. func (p IPPort) Port() uint16 { return p.port }
  976. // splitIPPort splits s into an IP address string and a port
  977. // string. It splits strings shaped like "foo:bar" or "[foo]:bar",
  978. // without further validating the substrings. v6 indicates whether the
  979. // ip string should parse as an IPv6 address or an IPv4 address, in
  980. // order for s to be a valid ip:port string.
  981. func splitIPPort(s string) (ip, port string, v6 bool, err error) {
  982. i := strings.LastIndexByte(s, ':')
  983. if i == -1 {
  984. return "", "", false, errors.New("not an ip:port")
  985. }
  986. ip, port = s[:i], s[i+1:]
  987. if len(ip) == 0 {
  988. return "", "", false, errors.New("no IP")
  989. }
  990. if len(port) == 0 {
  991. return "", "", false, errors.New("no port")
  992. }
  993. if ip[0] == '[' {
  994. if len(ip) < 2 || ip[len(ip)-1] != ']' {
  995. return "", "", false, errors.New("missing ]")
  996. }
  997. ip = ip[1 : len(ip)-1]
  998. v6 = true
  999. }
  1000. return ip, port, v6, nil
  1001. }
  1002. // ParseIPPort parses s as an IPPort.
  1003. //
  1004. // It doesn't do any name resolution, and ports must be numeric.
  1005. func ParseIPPort(s string) (IPPort, error) {
  1006. var ipp IPPort
  1007. ip, port, v6, err := splitIPPort(s)
  1008. if err != nil {
  1009. return ipp, err
  1010. }
  1011. port16, err := strconv.ParseUint(port, 10, 16)
  1012. if err != nil {
  1013. return ipp, fmt.Errorf("invalid port %q parsing %q", port, s)
  1014. }
  1015. ipp.port = uint16(port16)
  1016. ipp.ip, err = ParseIP(ip)
  1017. if err != nil {
  1018. return IPPort{}, err
  1019. }
  1020. if v6 && ipp.ip.Is4() {
  1021. return IPPort{}, fmt.Errorf("invalid ip:port %q, square brackets can only be used with IPv6 addresses", s)
  1022. } else if !v6 && ipp.ip.Is6() {
  1023. return IPPort{}, fmt.Errorf("invalid ip:port %q, IPv6 addresses must be surrounded by square brackets", s)
  1024. }
  1025. return ipp, nil
  1026. }
  1027. // MustParseIPPort calls ParseIPPort(s) and panics on error.
  1028. // It is intended for use in tests with hard-coded strings.
  1029. func MustParseIPPort(s string) IPPort {
  1030. ip, err := ParseIPPort(s)
  1031. if err != nil {
  1032. panic(err)
  1033. }
  1034. return ip
  1035. }
  1036. // IsZero reports whether p is its zero value.
  1037. func (p IPPort) IsZero() bool { return p == IPPort{} }
  1038. // IsValid reports whether p.IP() is valid.
  1039. // All ports are valid, including zero.
  1040. func (p IPPort) IsValid() bool { return p.ip.IsValid() }
  1041. // Valid reports whether p.IP() is valid.
  1042. // All ports are valid, including zero.
  1043. //
  1044. // Deprecated: use the correctly named and identical IsValid method instead.
  1045. func (p IPPort) Valid() bool { return p.IsValid() }
  1046. func (p IPPort) String() string {
  1047. switch p.ip.z {
  1048. case z0:
  1049. return "invalid IPPort"
  1050. case z4:
  1051. a := p.ip.As4()
  1052. return fmt.Sprintf("%d.%d.%d.%d:%d", a[0], a[1], a[2], a[3], p.port)
  1053. default:
  1054. // TODO: this could be more efficient allocation-wise:
  1055. return net.JoinHostPort(p.ip.String(), strconv.Itoa(int(p.port)))
  1056. }
  1057. }
  1058. // AppendTo appends a text encoding of p,
  1059. // as generated by MarshalText,
  1060. // to b and returns the extended buffer.
  1061. func (p IPPort) AppendTo(b []byte) []byte {
  1062. switch p.ip.z {
  1063. case z0:
  1064. return b
  1065. case z4:
  1066. b = p.ip.appendTo4(b)
  1067. default:
  1068. b = append(b, '[')
  1069. b = p.ip.appendTo6(b)
  1070. b = append(b, ']')
  1071. }
  1072. b = append(b, ':')
  1073. b = strconv.AppendInt(b, int64(p.port), 10)
  1074. return b
  1075. }
  1076. // MarshalText implements the encoding.TextMarshaler interface. The
  1077. // encoding is the same as returned by String, with one exception: if
  1078. // p.IP() is the zero value, the encoding is the empty string.
  1079. func (p IPPort) MarshalText() ([]byte, error) {
  1080. var max int
  1081. switch p.ip.z {
  1082. case z0:
  1083. case z4:
  1084. max = len("255.255.255.255:65535")
  1085. default:
  1086. max = len("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%enp5s0]:65535")
  1087. }
  1088. b := make([]byte, 0, max)
  1089. b = p.AppendTo(b)
  1090. return b, nil
  1091. }
  1092. // UnmarshalText implements the encoding.TextUnmarshaler
  1093. // interface. The IPPort is expected in a form accepted by
  1094. // ParseIPPort. It returns an error if *p is not the IPPort zero
  1095. // value.
  1096. func (p *IPPort) UnmarshalText(text []byte) error {
  1097. if p.ip.z != z0 || p.port != 0 {
  1098. return errors.New("refusing to Unmarshal into non-zero IPPort")
  1099. }
  1100. if len(text) == 0 {
  1101. return nil
  1102. }
  1103. var err error
  1104. *p, err = ParseIPPort(string(text))
  1105. return err
  1106. }
  1107. // FromStdAddr maps the components of a standard library TCPAddr or
  1108. // UDPAddr into an IPPort.
  1109. func FromStdAddr(stdIP net.IP, port int, zone string) (_ IPPort, ok bool) {
  1110. ip, ok := FromStdIP(stdIP)
  1111. if !ok || port < 0 || port > math.MaxUint16 {
  1112. return
  1113. }
  1114. ip = ip.Unmap()
  1115. if zone != "" {
  1116. if ip.Is4() {
  1117. ok = false
  1118. return
  1119. }
  1120. ip = ip.WithZone(zone)
  1121. }
  1122. return IPPort{ip: ip, port: uint16(port)}, true
  1123. }
  1124. // UDPAddr returns a standard library net.UDPAddr from p.
  1125. // The returned value is always non-nil. If p.IP() is the zero
  1126. // value, then UDPAddr.IP is nil.
  1127. //
  1128. // UDPAddr necessarily does two allocations. If you have an existing
  1129. // UDPAddr already allocated, see UDPAddrAt.
  1130. func (p IPPort) UDPAddr() *net.UDPAddr {
  1131. ret := &net.UDPAddr{
  1132. Port: int(p.port),
  1133. }
  1134. ret.IP, ret.Zone = p.ip.ipZone(nil)
  1135. return ret
  1136. }
  1137. // UDPAddrAt is like UDPAddr, but reuses the provided UDPAddr, which
  1138. // must be non-nil. If at.IP has a capacity of 16, UDPAddrAt is
  1139. // allocation-free. It returns at to facilitate using this method as a
  1140. // wrapper.
  1141. func (p IPPort) UDPAddrAt(at *net.UDPAddr) *net.UDPAddr {
  1142. at.Port = int(p.port)
  1143. at.IP, at.Zone = p.ip.ipZone(at.IP)
  1144. return at
  1145. }
  1146. // TCPAddr returns a standard library net.TCPAddr from p.
  1147. // The returned value is always non-nil. If p.IP() is the zero
  1148. // value, then TCPAddr.IP is nil.
  1149. func (p IPPort) TCPAddr() *net.TCPAddr {
  1150. ip, zone := p.ip.ipZone(nil)
  1151. return &net.TCPAddr{
  1152. IP: ip,
  1153. Port: int(p.port),
  1154. Zone: zone,
  1155. }
  1156. }
  1157. // IPPrefix is an IP address prefix (CIDR) representing an IP network.
  1158. //
  1159. // The first Bits() of IP() are specified. The remaining bits match any address.
  1160. // The range of Bits() is [0,32] for IPv4 or [0,128] for IPv6.
  1161. type IPPrefix struct {
  1162. ip IP
  1163. bits uint8
  1164. }
  1165. // IPPrefixFrom returns an IPPrefix with IP ip and provided bits prefix length.
  1166. // It does not allocate.
  1167. func IPPrefixFrom(ip IP, bits uint8) IPPrefix {
  1168. return IPPrefix{
  1169. ip: ip.withoutZone(),
  1170. bits: bits,
  1171. }
  1172. }
  1173. // IP returns p's IP.
  1174. func (p IPPrefix) IP() IP { return p.ip }
  1175. // Bits returns p's prefix length.
  1176. func (p IPPrefix) Bits() uint8 { return p.bits }
  1177. // IsValid reports whether whether p.Bits() has a valid range for p.IP().
  1178. // If p.IP() is zero, Valid returns false.
  1179. func (p IPPrefix) IsValid() bool { return !p.ip.IsZero() && p.bits <= p.ip.BitLen() }
  1180. // Valid reports whether whether p.Bits() has a valid range for p.IP().
  1181. // If p.IP() is zero, Valid returns false.
  1182. //
  1183. // Deprecated: use the correctly named and identical IsValid method instead.
  1184. func (p IPPrefix) Valid() bool { return p.IsValid() }
  1185. // IsZero reports whether p is its zero value.
  1186. func (p IPPrefix) IsZero() bool { return p == IPPrefix{} }
  1187. // IsSingleIP reports whether p contains exactly one IP.
  1188. func (p IPPrefix) IsSingleIP() bool { return p.bits != 0 && p.bits == p.ip.BitLen() }
  1189. // FromStdIPNet returns an IPPrefix from the standard library's IPNet type.
  1190. // If std is invalid, ok is false.
  1191. func FromStdIPNet(std *net.IPNet) (prefix IPPrefix, ok bool) {
  1192. ip, ok := FromStdIP(std.IP)
  1193. if !ok {
  1194. return IPPrefix{}, false
  1195. }
  1196. if l := len(std.Mask); l != net.IPv4len && l != net.IPv6len {
  1197. // Invalid mask.
  1198. return IPPrefix{}, false
  1199. }
  1200. ones, bits := std.Mask.Size()
  1201. if ones == 0 && bits == 0 {
  1202. // IPPrefix does not support non-contiguous masks.
  1203. return IPPrefix{}, false
  1204. }
  1205. return IPPrefix{
  1206. ip: ip,
  1207. bits: uint8(ones),
  1208. }, true
  1209. }
  1210. // ParseIPPrefix parses s as an IP address prefix.
  1211. // The string can be in the form "192.168.1.0/24" or "2001::db8::/32",
  1212. // the CIDR notation defined in RFC 4632 and RFC 4291.
  1213. //
  1214. // Note that masked address bits are not zeroed. Use Masked for that.
  1215. func ParseIPPrefix(s string) (IPPrefix, error) {
  1216. i := strings.LastIndexByte(s, '/')
  1217. if i < 0 {
  1218. return IPPrefix{}, fmt.Errorf("netaddr.ParseIPPrefix(%q): no '/'", s)
  1219. }
  1220. ip, err := ParseIP(s[:i])
  1221. if err != nil {
  1222. return IPPrefix{}, fmt.Errorf("netaddr.ParseIPPrefix(%q): %v", s, err)
  1223. }
  1224. s = s[i+1:]
  1225. bits, err := strconv.Atoi(s)
  1226. if err != nil {
  1227. return IPPrefix{}, fmt.Errorf("netaddr.ParseIPPrefix(%q): bad prefix: %v", s, err)
  1228. }
  1229. maxBits := 32
  1230. if ip.Is6() {
  1231. maxBits = 128
  1232. }
  1233. if bits < 0 || bits > maxBits {
  1234. return IPPrefix{}, fmt.Errorf("netaddr.ParseIPPrefix(%q): prefix length out of range", s)
  1235. }
  1236. return IPPrefixFrom(ip, uint8(bits)), nil
  1237. }
  1238. // MustParseIPPrefix calls ParseIPPrefix(s) and panics on error.
  1239. // It is intended for use in tests with hard-coded strings.
  1240. func MustParseIPPrefix(s string) IPPrefix {
  1241. ip, err := ParseIPPrefix(s)
  1242. if err != nil {
  1243. panic(err)
  1244. }
  1245. return ip
  1246. }
  1247. // Masked returns p in its canonical form, with bits of p.IP() not in p.Bits() masked off.
  1248. // If p is zero or otherwise invalid, Masked returns the zero value.
  1249. func (p IPPrefix) Masked() IPPrefix {
  1250. if m, err := p.ip.Prefix(p.bits); err == nil {
  1251. return m
  1252. }
  1253. return IPPrefix{}
  1254. }
  1255. // Range returns the inclusive range of IPs that p covers.
  1256. //
  1257. // If p is zero or otherwise invalid, Range returns the zero value.
  1258. func (p IPPrefix) Range() IPRange {
  1259. p = p.Masked()
  1260. if p.IsZero() {
  1261. return IPRange{}
  1262. }
  1263. return IPRangeFrom(p.ip, p.lastIP())
  1264. }
  1265. // IPNet returns the net.IPNet representation of an IPPrefix.
  1266. // The returned value is always non-nil.
  1267. // Any zone identifier is dropped in the conversion.
  1268. func (p IPPrefix) IPNet() *net.IPNet {
  1269. if !p.IsValid() {
  1270. return &net.IPNet{}
  1271. }
  1272. stdIP, _ := p.ip.ipZone(nil)
  1273. return &net.IPNet{
  1274. IP: stdIP,
  1275. Mask: net.CIDRMask(int(p.bits), int(p.ip.BitLen())),
  1276. }
  1277. }
  1278. // Contains reports whether the network p includes ip.
  1279. //
  1280. // An IPv4 address will not match an IPv6 prefix.
  1281. // A v6-mapped IPv6 address will not match an IPv4 prefix.
  1282. // A zero-value IP will not match any prefix.
  1283. // If ip has an IPv6 zone, Contains returns false,
  1284. // because IPPrefixes strip zones.
  1285. func (p IPPrefix) Contains(ip IP) bool {
  1286. if !p.IsValid() || ip.hasZone() {
  1287. return false
  1288. }
  1289. if f1, f2 := p.ip.BitLen(), ip.BitLen(); f1 == 0 || f2 == 0 || f1 != f2 {
  1290. return false
  1291. }
  1292. if ip.Is4() {
  1293. // xor the IP addresses together; mismatched bits are now ones.
  1294. // Shift away the number of bits we don't care about.
  1295. // Shifts in Go are more efficient if the compiler can prove
  1296. // that the shift amount is smaller than the width of the shifted type (64 here).
  1297. // We know that p.bits is in the range 0..32 because p is Valid;
  1298. // the compiler doesn't know that, so mask with 63 to help it.
  1299. // Now truncate to 32 bits, because this is IPv4.
  1300. // If all the bits we care about are equal, the result will be zero.
  1301. return uint32((ip.addr.lo^p.ip.addr.lo)>>((32-p.bits)&63)) == 0
  1302. } else {
  1303. // xor the IP addresses together.
  1304. // Mask away the bits we don't care about.
  1305. // If all the bits we care about are equal, the result will be zero.
  1306. return ip.addr.xor(p.ip.addr).and(mask6[p.bits]).isZero()
  1307. }
  1308. }
  1309. // Overlaps reports whether p and o overlap at all.
  1310. //
  1311. // If p and o are of different address families or either have a zero
  1312. // IP, it reports false. Like the Contains method, a prefix with a
  1313. // v6-mapped IPv4 IP is still treated as an IPv6 mask.
  1314. //
  1315. // If either has a Bits of zero, it returns true.
  1316. func (p IPPrefix) Overlaps(o IPPrefix) bool {
  1317. if !p.IsValid() || !o.IsValid() {
  1318. return false
  1319. }
  1320. if p == o {
  1321. return true
  1322. }
  1323. if p.ip.Is4() != o.ip.Is4() {
  1324. return false
  1325. }
  1326. var minBits uint8
  1327. if p.bits < o.bits {
  1328. minBits = p.bits
  1329. } else {
  1330. minBits = o.bits
  1331. }
  1332. if minBits == 0 {
  1333. return true
  1334. }
  1335. // One of these Prefix calls might look redundant, but we don't require
  1336. // that p and o values are normalized (via IPPrefix.Masked) first,
  1337. // so the Prefix call on the one that's already minBits serves to zero
  1338. // out any remaining bits in IP.
  1339. var err error
  1340. if p, err = p.ip.Prefix(minBits); err != nil {
  1341. return false
  1342. }
  1343. if o, err = o.ip.Prefix(minBits); err != nil {
  1344. return false
  1345. }
  1346. return p.ip == o.ip
  1347. }
  1348. // AppendTo appends a text encoding of p,
  1349. // as generated by MarshalText,
  1350. // to b and returns the extended buffer.
  1351. func (p IPPrefix) AppendTo(b []byte) []byte {
  1352. if p.IsZero() {
  1353. return b
  1354. }
  1355. if !p.IsValid() {
  1356. return append(b, "invalid IPPrefix"...)
  1357. }
  1358. // p.IP is non-zero, because p is valid.
  1359. if p.ip.z == z4 {
  1360. b = p.ip.appendTo4(b)
  1361. } else {
  1362. b = p.ip.appendTo6(b)
  1363. }
  1364. b = append(b, '/')
  1365. b = appendDecimal(b, p.bits)
  1366. return b
  1367. }
  1368. // MarshalText implements the encoding.TextMarshaler interface,
  1369. // The encoding is the same as returned by String, with one exception:
  1370. // If p is the zero value, the encoding is the empty string.
  1371. func (p IPPrefix) MarshalText() ([]byte, error) {
  1372. var max int
  1373. switch p.ip.z {
  1374. case z0:
  1375. case z4:
  1376. max = len("255.255.255.255/32")
  1377. default:
  1378. max = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%enp5s0/128")
  1379. }
  1380. b := make([]byte, 0, max)
  1381. b = p.AppendTo(b)
  1382. return b, nil
  1383. }
  1384. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  1385. // The IP address is expected in a form accepted by ParseIPPrefix.
  1386. // It returns an error if *p is not the IPPrefix zero value.
  1387. func (p *IPPrefix) UnmarshalText(text []byte) error {
  1388. if *p != (IPPrefix{}) {
  1389. return errors.New("refusing to Unmarshal into non-zero IPPrefix")
  1390. }
  1391. if len(text) == 0 {
  1392. return nil
  1393. }
  1394. var err error
  1395. *p, err = ParseIPPrefix(string(text))
  1396. return err
  1397. }
  1398. // String returns the CIDR notation of p: "<ip>/<bits>".
  1399. func (p IPPrefix) String() string {
  1400. if p.IsZero() {
  1401. return "zero IPPrefix"
  1402. }
  1403. if !p.IsValid() {
  1404. return "invalid IPPrefix"
  1405. }
  1406. return fmt.Sprintf("%s/%d", p.ip, p.bits)
  1407. }
  1408. // lastIP returns the last IP in the prefix.
  1409. func (p IPPrefix) lastIP() IP {
  1410. if !p.IsValid() {
  1411. return IP{}
  1412. }
  1413. a16 := p.ip.As16()
  1414. var off uint8
  1415. var bits uint8 = 128
  1416. if p.ip.Is4() {
  1417. off = 12
  1418. bits = 32
  1419. }
  1420. for b := p.bits; b < bits; b++ {
  1421. byteNum, bitInByte := b/8, 7-(b%8)
  1422. a16[off+byteNum] |= 1 << uint(bitInByte)
  1423. }
  1424. if p.ip.Is4() {
  1425. return IPFrom16(a16)
  1426. } else {
  1427. return IPv6Raw(a16) // doesn't unmap
  1428. }
  1429. }
  1430. // IPRange represents an inclusive range of IP addresses
  1431. // from the same address family.
  1432. //
  1433. // The From() and To() IPs are inclusive bounds, both included in the
  1434. // range.
  1435. //
  1436. // To be valid, the From() and To() values must be non-zero, have matching
  1437. // address families (IPv4 vs IPv6), and From() must be less than or equal to To().
  1438. // IPv6 zones are stripped out and ignored.
  1439. // An invalid range may be ignored.
  1440. type IPRange struct {
  1441. // from is the initial IP address in the range.
  1442. from IP
  1443. // to is the final IP address in the range.
  1444. to IP
  1445. }
  1446. // IPRangeFrom returns an IPRange from from to to.
  1447. // It does not allocate.
  1448. func IPRangeFrom(from, to IP) IPRange {
  1449. return IPRange{
  1450. from: from.withoutZone(),
  1451. to: to.withoutZone(),
  1452. }
  1453. }
  1454. // From returns the lower bound of r.
  1455. func (r IPRange) From() IP { return r.from }
  1456. // To returns the upper bound of r.
  1457. func (r IPRange) To() IP { return r.to }
  1458. // ParseIPRange parses a range out of two IPs separated by a hyphen.
  1459. //
  1460. // It returns an error if the range is not valid.
  1461. func ParseIPRange(s string) (IPRange, error) {
  1462. var r IPRange
  1463. h := strings.IndexByte(s, '-')
  1464. if h == -1 {
  1465. return r, fmt.Errorf("no hyphen in range %q", s)
  1466. }
  1467. from, to := s[:h], s[h+1:]
  1468. var err error
  1469. r.from, err = ParseIP(from)
  1470. if err != nil {
  1471. return r, fmt.Errorf("invalid From IP %q in range %q", from, s)
  1472. }
  1473. r.from = r.from.withoutZone()
  1474. r.to, err = ParseIP(to)
  1475. if err != nil {
  1476. return r, fmt.Errorf("invalid To IP %q in range %q", to, s)
  1477. }
  1478. r.to = r.to.withoutZone()
  1479. if !r.IsValid() {
  1480. return r, fmt.Errorf("range %v to %v not valid", r.from, r.to)
  1481. }
  1482. return r, nil
  1483. }
  1484. // MustParseIPRange calls ParseIPRange(s) and panics on error.
  1485. // It is intended for use in tests with hard-coded strings.
  1486. func MustParseIPRange(s string) IPRange {
  1487. r, err := ParseIPRange(s)
  1488. if err != nil {
  1489. panic(err)
  1490. }
  1491. return r
  1492. }
  1493. // String returns a string representation of the range.
  1494. //
  1495. // For a valid range, the form is "From-To" with a single hyphen
  1496. // separating the IPs, the same format recognized by
  1497. // ParseIPRange.
  1498. func (r IPRange) String() string {
  1499. if r.IsValid() {
  1500. return fmt.Sprintf("%s-%s", r.from, r.to)
  1501. }
  1502. if r.from.IsZero() || r.to.IsZero() {
  1503. return "zero IPRange"
  1504. }
  1505. return "invalid IPRange"
  1506. }
  1507. // AppendTo appends a text encoding of r,
  1508. // as generated by MarshalText,
  1509. // to b and returns the extended buffer.
  1510. func (r IPRange) AppendTo(b []byte) []byte {
  1511. if r.IsZero() {
  1512. return b
  1513. }
  1514. b = r.from.AppendTo(b)
  1515. b = append(b, '-')
  1516. b = r.to.AppendTo(b)
  1517. return b
  1518. }
  1519. // MarshalText implements the encoding.TextMarshaler interface,
  1520. // The encoding is the same as returned by String, with one exception:
  1521. // If ip is the zero value, the encoding is the empty string.
  1522. func (r IPRange) MarshalText() ([]byte, error) {
  1523. if r.IsZero() {
  1524. return []byte(""), nil
  1525. }
  1526. var max int
  1527. if r.from.z == z4 {
  1528. max = len("255.255.255.255-255.255.255.255")
  1529. } else {
  1530. max = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
  1531. }
  1532. b := make([]byte, 0, max)
  1533. return r.AppendTo(b), nil
  1534. }
  1535. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  1536. // The IP range is expected in a form accepted by ParseIPRange.
  1537. // It returns an error if *r is not the IPRange zero value.
  1538. func (r *IPRange) UnmarshalText(text []byte) error {
  1539. if *r != (IPRange{}) {
  1540. return errors.New("refusing to Unmarshal into non-zero IPRange")
  1541. }
  1542. if len(text) == 0 {
  1543. return nil
  1544. }
  1545. var err error
  1546. *r, err = ParseIPRange(string(text))
  1547. return err
  1548. }
  1549. // IsZero reports whether r is the zero value of the IPRange type.
  1550. func (r IPRange) IsZero() bool {
  1551. return r == IPRange{}
  1552. }
  1553. // IsValid reports whether r.From() and r.To() are both non-zero and
  1554. // obey the documented requirements: address families match, and From
  1555. // is less than or equal to To.
  1556. func (r IPRange) IsValid() bool {
  1557. return !r.from.IsZero() &&
  1558. r.from.z == r.to.z &&
  1559. !r.to.Less(r.from)
  1560. }
  1561. // Valid reports whether r.From() and r.To() are both non-zero and
  1562. // obey the documented requirements: address families match, and From
  1563. // is less than or equal to To.
  1564. //
  1565. // Deprecated: use the correctly named and identical IsValid method instead.
  1566. func (r IPRange) Valid() bool { return r.IsValid() }
  1567. // Contains reports whether the range r includes addr.
  1568. //
  1569. // An invalid range always reports false.
  1570. //
  1571. // If ip has an IPv6 zone, Contains returns false,
  1572. // because IPPrefixes strip zones.
  1573. func (r IPRange) Contains(addr IP) bool {
  1574. return r.IsValid() && !addr.hasZone() && r.contains(addr)
  1575. }
  1576. // contains is like Contains, but without the validity check.
  1577. // addr must not have a zone.
  1578. func (r IPRange) contains(addr IP) bool {
  1579. return r.from.Compare(addr) <= 0 && r.to.Compare(addr) >= 0
  1580. }
  1581. // less reports whether r is "before" other. It is before if r.From()
  1582. // is before other.From(). If they're equal, then the larger range
  1583. // (higher To()) comes first.
  1584. func (r IPRange) less(other IPRange) bool {
  1585. if cmp := r.from.Compare(other.from); cmp != 0 {
  1586. return cmp < 0
  1587. }
  1588. return other.to.Less(r.to)
  1589. }
  1590. // entirelyBefore returns whether r lies entirely before other in IP
  1591. // space.
  1592. func (r IPRange) entirelyBefore(other IPRange) bool {
  1593. return r.to.Less(other.from)
  1594. }
  1595. // entirelyWithin returns whether r is entirely contained within
  1596. // other.
  1597. func (r IPRange) coveredBy(other IPRange) bool {
  1598. return other.from.lessOrEq(r.from) && r.to.lessOrEq(other.to)
  1599. }
  1600. // inMiddleOf returns whether r is inside other, but not touching the
  1601. // edges of other.
  1602. func (r IPRange) inMiddleOf(other IPRange) bool {
  1603. return other.from.Less(r.from) && r.to.Less(other.to)
  1604. }
  1605. // overlapsStartOf returns whether r entirely overlaps the start of
  1606. // other, but not all of other.
  1607. func (r IPRange) overlapsStartOf(other IPRange) bool {
  1608. return r.from.lessOrEq(other.from) && r.to.Less(other.to)
  1609. }
  1610. // overlapsEndOf returns whether r entirely overlaps the end of
  1611. // other, but not all of other.
  1612. func (r IPRange) overlapsEndOf(other IPRange) bool {
  1613. return other.from.Less(r.from) && other.to.lessOrEq(r.to)
  1614. }
  1615. // mergeIPRanges returns the minimum and sorted set of IP ranges that
  1616. // cover r.
  1617. func mergeIPRanges(rr []IPRange) (out []IPRange, valid bool) {
  1618. // Always return a copy of r, to avoid aliasing slice memory in
  1619. // the caller.
  1620. switch len(rr) {
  1621. case 0:
  1622. return nil, true
  1623. case 1:
  1624. return []IPRange{rr[0]}, true
  1625. }
  1626. sort.Slice(rr, func(i, j int) bool { return rr[i].less(rr[j]) })
  1627. out = make([]IPRange, 1, len(rr))
  1628. out[0] = rr[0]
  1629. for _, r := range rr[1:] {
  1630. prev := &out[len(out)-1]
  1631. switch {
  1632. case !r.IsValid():
  1633. // Invalid ranges make no sense to merge, refuse to
  1634. // perform.
  1635. return nil, false
  1636. case prev.to.Next() == r.from:
  1637. // prev and r touch, merge them.
  1638. //
  1639. // prev r
  1640. // f------tf-----t
  1641. prev.to = r.to
  1642. case prev.to.Less(r.from):
  1643. // No overlap and not adjacent (per previous case), no
  1644. // merging possible.
  1645. //
  1646. // prev r
  1647. // f------t f-----t
  1648. out = append(out, r)
  1649. case prev.to.Less(r.to):
  1650. // Partial overlap, update prev
  1651. //
  1652. // prev
  1653. // f------t
  1654. // f-----t
  1655. // r
  1656. prev.to = r.to
  1657. default:
  1658. // r entirely contained in prev, nothing to do.
  1659. //
  1660. // prev
  1661. // f--------t
  1662. // f-----t
  1663. // r
  1664. }
  1665. }
  1666. return out, true
  1667. }
  1668. // Overlaps reports whether p and o overlap at all.
  1669. //
  1670. // If p and o are of different address families or either are invalid,
  1671. // it reports false.
  1672. func (r IPRange) Overlaps(o IPRange) bool {
  1673. return r.IsValid() &&
  1674. o.IsValid() &&
  1675. r.from.Compare(o.to) <= 0 &&
  1676. o.from.Compare(r.to) <= 0
  1677. }
  1678. // prefixMaker returns a address-family-corrected IPPrefix from a and bits,
  1679. // where the input bits is always in the IPv6-mapped form for IPv4 addresses.
  1680. type prefixMaker func(a uint128, bits uint8) IPPrefix
  1681. // Prefixes returns the set of IPPrefix entries that covers r.
  1682. //
  1683. // If either of r's bounds are invalid, in the wrong order, or if
  1684. // they're of different address families, then Prefixes returns nil.
  1685. //
  1686. // Prefixes necessarily allocates. See AppendPrefixes for a version that uses
  1687. // memory you provide.
  1688. func (r IPRange) Prefixes() []IPPrefix {
  1689. return r.AppendPrefixes(nil)
  1690. }
  1691. // AppendPrefixes is an append version of IPRange.Prefixes. It appends
  1692. // the IPPrefix entries that cover r to dst.
  1693. func (r IPRange) AppendPrefixes(dst []IPPrefix) []IPPrefix {
  1694. if !r.IsValid() {
  1695. return nil
  1696. }
  1697. return appendRangePrefixes(dst, r.prefixFrom128AndBits, r.from.addr, r.to.addr)
  1698. }
  1699. func (r IPRange) prefixFrom128AndBits(a uint128, bits uint8) IPPrefix {
  1700. ip := IP{addr: a, z: r.from.z}
  1701. if r.from.Is4() {
  1702. bits -= 12 * 8
  1703. }
  1704. return IPPrefix{ip, bits}
  1705. }
  1706. // aZeroBSet is whether, after the common bits, a is all zero bits and
  1707. // b is all set (one) bits.
  1708. func comparePrefixes(a, b uint128) (common uint8, aZeroBSet bool) {
  1709. common = a.commonPrefixLen(b)
  1710. // See whether a and b, after their common shared bits, end
  1711. // in all zero bits or all one bits, respectively.
  1712. if common == 128 {
  1713. return common, true
  1714. }
  1715. m := mask6[common]
  1716. return common, (a.xor(a.and(m)).isZero() &&
  1717. b.or(m) == uint128{^uint64(0), ^uint64(0)})
  1718. }
  1719. // Prefix returns r as an IPPrefix, if it can be presented exactly as such.
  1720. // If r is not valid or is not exactly equal to one prefix, ok is false.
  1721. func (r IPRange) Prefix() (p IPPrefix, ok bool) {
  1722. if !r.IsValid() {
  1723. return
  1724. }
  1725. if common, ok := comparePrefixes(r.from.addr, r.to.addr); ok {
  1726. return r.prefixFrom128AndBits(r.from.addr, common), true
  1727. }
  1728. return
  1729. }
  1730. func appendRangePrefixes(dst []IPPrefix, makePrefix prefixMaker, a, b uint128) []IPPrefix {
  1731. common, ok := comparePrefixes(a, b)
  1732. if ok {
  1733. // a to b represents a whole range, like 10.50.0.0/16.
  1734. // (a being 10.50.0.0 and b being 10.50.255.255)
  1735. return append(dst, makePrefix(a, common))
  1736. }
  1737. // Otherwise recursively do both halves.
  1738. dst = appendRangePrefixes(dst, makePrefix, a, a.bitsSetFrom(common+1))
  1739. dst = appendRangePrefixes(dst, makePrefix, b.bitsClearedFrom(common+1), b)
  1740. return dst
  1741. }