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