github.com/ActiveState/go@v0.0.0-20170614201249-0b81c023a722/src/net/ip.go (about) 1 // Copyright 2009 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 // IP address manipulations 6 // 7 // IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes. 8 // An IPv4 address can be converted to an IPv6 address by 9 // adding a canonical prefix (10 zeros, 2 0xFFs). 10 // This library accepts either size of byte slice but always 11 // returns 16-byte addresses. 12 13 package net 14 15 import _ "unsafe" // for go:linkname 16 17 // IP address lengths (bytes). 18 const ( 19 IPv4len = 4 20 IPv6len = 16 21 ) 22 23 // An IP is a single IP address, a slice of bytes. 24 // Functions in this package accept either 4-byte (IPv4) 25 // or 16-byte (IPv6) slices as input. 26 // 27 // Note that in this documentation, referring to an 28 // IP address as an IPv4 address or an IPv6 address 29 // is a semantic property of the address, not just the 30 // length of the byte slice: a 16-byte slice can still 31 // be an IPv4 address. 32 type IP []byte 33 34 // An IP mask is an IP address. 35 type IPMask []byte 36 37 // An IPNet represents an IP network. 38 type IPNet struct { 39 IP IP // network number 40 Mask IPMask // network mask 41 } 42 43 // IPv4 returns the IP address (in 16-byte form) of the 44 // IPv4 address a.b.c.d. 45 func IPv4(a, b, c, d byte) IP { 46 p := make(IP, IPv6len) 47 copy(p, v4InV6Prefix) 48 p[12] = a 49 p[13] = b 50 p[14] = c 51 p[15] = d 52 return p 53 } 54 55 var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff} 56 57 // IPv4Mask returns the IP mask (in 4-byte form) of the 58 // IPv4 mask a.b.c.d. 59 func IPv4Mask(a, b, c, d byte) IPMask { 60 p := make(IPMask, IPv4len) 61 p[0] = a 62 p[1] = b 63 p[2] = c 64 p[3] = d 65 return p 66 } 67 68 // CIDRMask returns an IPMask consisting of `ones' 1 bits 69 // followed by 0s up to a total length of `bits' bits. 70 // For a mask of this form, CIDRMask is the inverse of IPMask.Size. 71 func CIDRMask(ones, bits int) IPMask { 72 if bits != 8*IPv4len && bits != 8*IPv6len { 73 return nil 74 } 75 if ones < 0 || ones > bits { 76 return nil 77 } 78 l := bits / 8 79 m := make(IPMask, l) 80 n := uint(ones) 81 for i := 0; i < l; i++ { 82 if n >= 8 { 83 m[i] = 0xff 84 n -= 8 85 continue 86 } 87 m[i] = ^byte(0xff >> n) 88 n = 0 89 } 90 return m 91 } 92 93 // Well-known IPv4 addresses 94 var ( 95 IPv4bcast = IPv4(255, 255, 255, 255) // limited broadcast 96 IPv4allsys = IPv4(224, 0, 0, 1) // all systems 97 IPv4allrouter = IPv4(224, 0, 0, 2) // all routers 98 IPv4zero = IPv4(0, 0, 0, 0) // all zeros 99 ) 100 101 // Well-known IPv6 addresses 102 var ( 103 IPv6zero = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 104 IPv6unspecified = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 105 IPv6loopback = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} 106 IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} 107 IPv6linklocalallnodes = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01} 108 IPv6linklocalallrouters = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02} 109 ) 110 111 // IsUnspecified reports whether ip is an unspecified address. 112 func (ip IP) IsUnspecified() bool { 113 return ip.Equal(IPv4zero) || ip.Equal(IPv6unspecified) 114 } 115 116 // IsLoopback reports whether ip is a loopback address. 117 func (ip IP) IsLoopback() bool { 118 if ip4 := ip.To4(); ip4 != nil { 119 return ip4[0] == 127 120 } 121 return ip.Equal(IPv6loopback) 122 } 123 124 // IsMulticast reports whether ip is a multicast address. 125 func (ip IP) IsMulticast() bool { 126 if ip4 := ip.To4(); ip4 != nil { 127 return ip4[0]&0xf0 == 0xe0 128 } 129 return len(ip) == IPv6len && ip[0] == 0xff 130 } 131 132 // IsInterfaceLocalMulticast reports whether ip is 133 // an interface-local multicast address. 134 func (ip IP) IsInterfaceLocalMulticast() bool { 135 return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x01 136 } 137 138 // IsLinkLocalMulticast reports whether ip is a link-local 139 // multicast address. 140 func (ip IP) IsLinkLocalMulticast() bool { 141 if ip4 := ip.To4(); ip4 != nil { 142 return ip4[0] == 224 && ip4[1] == 0 && ip4[2] == 0 143 } 144 return len(ip) == IPv6len && ip[0] == 0xff && ip[1]&0x0f == 0x02 145 } 146 147 // IsLinkLocalUnicast reports whether ip is a link-local 148 // unicast address. 149 func (ip IP) IsLinkLocalUnicast() bool { 150 if ip4 := ip.To4(); ip4 != nil { 151 return ip4[0] == 169 && ip4[1] == 254 152 } 153 return len(ip) == IPv6len && ip[0] == 0xfe && ip[1]&0xc0 == 0x80 154 } 155 156 // IsGlobalUnicast reports whether ip is a global unicast 157 // address. 158 // 159 // The identification of global unicast addresses uses address type 160 // identification as defined in RFC 1122, RFC 4632 and RFC 4291 with 161 // the exception of IPv4 directed broadcast addresses. 162 // It returns true even if ip is in IPv4 private address space or 163 // local IPv6 unicast address space. 164 func (ip IP) IsGlobalUnicast() bool { 165 return (len(ip) == IPv4len || len(ip) == IPv6len) && 166 !ip.Equal(IPv4bcast) && 167 !ip.IsUnspecified() && 168 !ip.IsLoopback() && 169 !ip.IsMulticast() && 170 !ip.IsLinkLocalUnicast() 171 } 172 173 // Is p all zeros? 174 func isZeros(p IP) bool { 175 for i := 0; i < len(p); i++ { 176 if p[i] != 0 { 177 return false 178 } 179 } 180 return true 181 } 182 183 // To4 converts the IPv4 address ip to a 4-byte representation. 184 // If ip is not an IPv4 address, To4 returns nil. 185 func (ip IP) To4() IP { 186 if len(ip) == IPv4len { 187 return ip 188 } 189 if len(ip) == IPv6len && 190 isZeros(ip[0:10]) && 191 ip[10] == 0xff && 192 ip[11] == 0xff { 193 return ip[12:16] 194 } 195 return nil 196 } 197 198 // To16 converts the IP address ip to a 16-byte representation. 199 // If ip is not an IP address (it is the wrong length), To16 returns nil. 200 func (ip IP) To16() IP { 201 if len(ip) == IPv4len { 202 return IPv4(ip[0], ip[1], ip[2], ip[3]) 203 } 204 if len(ip) == IPv6len { 205 return ip 206 } 207 return nil 208 } 209 210 // Default route masks for IPv4. 211 var ( 212 classAMask = IPv4Mask(0xff, 0, 0, 0) 213 classBMask = IPv4Mask(0xff, 0xff, 0, 0) 214 classCMask = IPv4Mask(0xff, 0xff, 0xff, 0) 215 ) 216 217 // DefaultMask returns the default IP mask for the IP address ip. 218 // Only IPv4 addresses have default masks; DefaultMask returns 219 // nil if ip is not a valid IPv4 address. 220 func (ip IP) DefaultMask() IPMask { 221 if ip = ip.To4(); ip == nil { 222 return nil 223 } 224 switch true { 225 case ip[0] < 0x80: 226 return classAMask 227 case ip[0] < 0xC0: 228 return classBMask 229 default: 230 return classCMask 231 } 232 } 233 234 func allFF(b []byte) bool { 235 for _, c := range b { 236 if c != 0xff { 237 return false 238 } 239 } 240 return true 241 } 242 243 // Mask returns the result of masking the IP address ip with mask. 244 func (ip IP) Mask(mask IPMask) IP { 245 if len(mask) == IPv6len && len(ip) == IPv4len && allFF(mask[:12]) { 246 mask = mask[12:] 247 } 248 if len(mask) == IPv4len && len(ip) == IPv6len && bytesEqual(ip[:12], v4InV6Prefix) { 249 ip = ip[12:] 250 } 251 n := len(ip) 252 if n != len(mask) { 253 return nil 254 } 255 out := make(IP, n) 256 for i := 0; i < n; i++ { 257 out[i] = ip[i] & mask[i] 258 } 259 return out 260 } 261 262 // String returns the string form of the IP address ip. 263 // It returns one of 4 forms: 264 // - "<nil>", if ip has length 0 265 // - dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address 266 // - IPv6 ("2001:db8::1"), if ip is a valid IPv6 address 267 // - the hexadecimal form of ip, without punctuation, if no other cases apply 268 func (ip IP) String() string { 269 p := ip 270 271 if len(ip) == 0 { 272 return "<nil>" 273 } 274 275 // If IPv4, use dotted notation. 276 if p4 := p.To4(); len(p4) == IPv4len { 277 return uitoa(uint(p4[0])) + "." + 278 uitoa(uint(p4[1])) + "." + 279 uitoa(uint(p4[2])) + "." + 280 uitoa(uint(p4[3])) 281 } 282 if len(p) != IPv6len { 283 return "?" + hexString(ip) 284 } 285 286 // Find longest run of zeros. 287 e0 := -1 288 e1 := -1 289 for i := 0; i < IPv6len; i += 2 { 290 j := i 291 for j < IPv6len && p[j] == 0 && p[j+1] == 0 { 292 j += 2 293 } 294 if j > i && j-i > e1-e0 { 295 e0 = i 296 e1 = j 297 i = j 298 } 299 } 300 // The symbol "::" MUST NOT be used to shorten just one 16 bit 0 field. 301 if e1-e0 <= 2 { 302 e0 = -1 303 e1 = -1 304 } 305 306 const maxLen = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") 307 b := make([]byte, 0, maxLen) 308 309 // Print with possible :: in place of run of zeros 310 for i := 0; i < IPv6len; i += 2 { 311 if i == e0 { 312 b = append(b, ':', ':') 313 i = e1 314 if i >= IPv6len { 315 break 316 } 317 } else if i > 0 { 318 b = append(b, ':') 319 } 320 b = appendHex(b, (uint32(p[i])<<8)|uint32(p[i+1])) 321 } 322 return string(b) 323 } 324 325 func hexString(b []byte) string { 326 s := make([]byte, len(b)*2) 327 for i, tn := range b { 328 s[i*2], s[i*2+1] = hexDigit[tn>>4], hexDigit[tn&0xf] 329 } 330 return string(s) 331 } 332 333 // ipEmptyString is like ip.String except that it returns 334 // an empty string when ip is unset. 335 func ipEmptyString(ip IP) string { 336 if len(ip) == 0 { 337 return "" 338 } 339 return ip.String() 340 } 341 342 // MarshalText implements the encoding.TextMarshaler interface. 343 // The encoding is the same as returned by String, with one exception: 344 // When len(ip) is zero, it returns an empty slice. 345 func (ip IP) MarshalText() ([]byte, error) { 346 if len(ip) == 0 { 347 return []byte(""), nil 348 } 349 if len(ip) != IPv4len && len(ip) != IPv6len { 350 return nil, &AddrError{Err: "invalid IP address", Addr: hexString(ip)} 351 } 352 return []byte(ip.String()), nil 353 } 354 355 // UnmarshalText implements the encoding.TextUnmarshaler interface. 356 // The IP address is expected in a form accepted by ParseIP. 357 func (ip *IP) UnmarshalText(text []byte) error { 358 if len(text) == 0 { 359 *ip = nil 360 return nil 361 } 362 s := string(text) 363 x := ParseIP(s) 364 if x == nil { 365 return &ParseError{Type: "IP address", Text: s} 366 } 367 *ip = x 368 return nil 369 } 370 371 // Equal reports whether ip and x are the same IP address. 372 // An IPv4 address and that same address in IPv6 form are 373 // considered to be equal. 374 func (ip IP) Equal(x IP) bool { 375 if len(ip) == len(x) { 376 return bytesEqual(ip, x) 377 } 378 if len(ip) == IPv4len && len(x) == IPv6len { 379 return bytesEqual(x[0:12], v4InV6Prefix) && bytesEqual(ip, x[12:]) 380 } 381 if len(ip) == IPv6len && len(x) == IPv4len { 382 return bytesEqual(ip[0:12], v4InV6Prefix) && bytesEqual(ip[12:], x) 383 } 384 return false 385 } 386 387 // bytes.Equal is implemented in runtime/asm_$goarch.s 388 //go:linkname bytesEqual bytes.Equal 389 func bytesEqual(x, y []byte) bool 390 391 func (ip IP) matchAddrFamily(x IP) bool { 392 return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil 393 } 394 395 // If mask is a sequence of 1 bits followed by 0 bits, 396 // return the number of 1 bits. 397 func simpleMaskLength(mask IPMask) int { 398 var n int 399 for i, v := range mask { 400 if v == 0xff { 401 n += 8 402 continue 403 } 404 // found non-ff byte 405 // count 1 bits 406 for v&0x80 != 0 { 407 n++ 408 v <<= 1 409 } 410 // rest must be 0 bits 411 if v != 0 { 412 return -1 413 } 414 for i++; i < len(mask); i++ { 415 if mask[i] != 0 { 416 return -1 417 } 418 } 419 break 420 } 421 return n 422 } 423 424 // Size returns the number of leading ones and total bits in the mask. 425 // If the mask is not in the canonical form--ones followed by zeros--then 426 // Size returns 0, 0. 427 func (m IPMask) Size() (ones, bits int) { 428 ones, bits = simpleMaskLength(m), len(m)*8 429 if ones == -1 { 430 return 0, 0 431 } 432 return 433 } 434 435 // String returns the hexadecimal form of m, with no punctuation. 436 func (m IPMask) String() string { 437 if len(m) == 0 { 438 return "<nil>" 439 } 440 return hexString(m) 441 } 442 443 func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) { 444 if ip = n.IP.To4(); ip == nil { 445 ip = n.IP 446 if len(ip) != IPv6len { 447 return nil, nil 448 } 449 } 450 m = n.Mask 451 switch len(m) { 452 case IPv4len: 453 if len(ip) != IPv4len { 454 return nil, nil 455 } 456 case IPv6len: 457 if len(ip) == IPv4len { 458 m = m[12:] 459 } 460 default: 461 return nil, nil 462 } 463 return 464 } 465 466 // Contains reports whether the network includes ip. 467 func (n *IPNet) Contains(ip IP) bool { 468 nn, m := networkNumberAndMask(n) 469 if x := ip.To4(); x != nil { 470 ip = x 471 } 472 l := len(ip) 473 if l != len(nn) { 474 return false 475 } 476 for i := 0; i < l; i++ { 477 if nn[i]&m[i] != ip[i]&m[i] { 478 return false 479 } 480 } 481 return true 482 } 483 484 // Network returns the address's network name, "ip+net". 485 func (n *IPNet) Network() string { return "ip+net" } 486 487 // String returns the CIDR notation of n like "192.0.2.1/24" 488 // or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. 489 // If the mask is not in the canonical form, it returns the 490 // string which consists of an IP address, followed by a slash 491 // character and a mask expressed as hexadecimal form with no 492 // punctuation like "198.51.100.1/c000ff00". 493 func (n *IPNet) String() string { 494 nn, m := networkNumberAndMask(n) 495 if nn == nil || m == nil { 496 return "<nil>" 497 } 498 l := simpleMaskLength(m) 499 if l == -1 { 500 return nn.String() + "/" + m.String() 501 } 502 return nn.String() + "/" + uitoa(uint(l)) 503 } 504 505 // Parse IPv4 address (d.d.d.d). 506 func parseIPv4(s string) IP { 507 var p [IPv4len]byte 508 for i := 0; i < IPv4len; i++ { 509 if len(s) == 0 { 510 // Missing octets. 511 return nil 512 } 513 if i > 0 { 514 if s[0] != '.' { 515 return nil 516 } 517 s = s[1:] 518 } 519 n, c, ok := dtoi(s) 520 if !ok || n > 0xFF { 521 return nil 522 } 523 s = s[c:] 524 p[i] = byte(n) 525 } 526 if len(s) != 0 { 527 return nil 528 } 529 return IPv4(p[0], p[1], p[2], p[3]) 530 } 531 532 // parseIPv6 parses s as a literal IPv6 address described in RFC 4291 533 // and RFC 5952. It can also parse a literal scoped IPv6 address with 534 // zone identifier which is described in RFC 4007 when zoneAllowed is 535 // true. 536 func parseIPv6(s string, zoneAllowed bool) (ip IP, zone string) { 537 ip = make(IP, IPv6len) 538 ellipsis := -1 // position of ellipsis in ip 539 540 if zoneAllowed { 541 s, zone = splitHostZone(s) 542 } 543 544 // Might have leading ellipsis 545 if len(s) >= 2 && s[0] == ':' && s[1] == ':' { 546 ellipsis = 0 547 s = s[2:] 548 // Might be only ellipsis 549 if len(s) == 0 { 550 return ip, zone 551 } 552 } 553 554 // Loop, parsing hex numbers followed by colon. 555 i := 0 556 for i < IPv6len { 557 // Hex number. 558 n, c, ok := xtoi(s) 559 if !ok || n > 0xFFFF { 560 return nil, zone 561 } 562 563 // If followed by dot, might be in trailing IPv4. 564 if c < len(s) && s[c] == '.' { 565 if ellipsis < 0 && i != IPv6len-IPv4len { 566 // Not the right place. 567 return nil, zone 568 } 569 if i+IPv4len > IPv6len { 570 // Not enough room. 571 return nil, zone 572 } 573 ip4 := parseIPv4(s) 574 if ip4 == nil { 575 return nil, zone 576 } 577 ip[i] = ip4[12] 578 ip[i+1] = ip4[13] 579 ip[i+2] = ip4[14] 580 ip[i+3] = ip4[15] 581 s = "" 582 i += IPv4len 583 break 584 } 585 586 // Save this 16-bit chunk. 587 ip[i] = byte(n >> 8) 588 ip[i+1] = byte(n) 589 i += 2 590 591 // Stop at end of string. 592 s = s[c:] 593 if len(s) == 0 { 594 break 595 } 596 597 // Otherwise must be followed by colon and more. 598 if s[0] != ':' || len(s) == 1 { 599 return nil, zone 600 } 601 s = s[1:] 602 603 // Look for ellipsis. 604 if s[0] == ':' { 605 if ellipsis >= 0 { // already have one 606 return nil, zone 607 } 608 ellipsis = i 609 s = s[1:] 610 if len(s) == 0 { // can be at end 611 break 612 } 613 } 614 } 615 616 // Must have used entire string. 617 if len(s) != 0 { 618 return nil, zone 619 } 620 621 // If didn't parse enough, expand ellipsis. 622 if i < IPv6len { 623 if ellipsis < 0 { 624 return nil, zone 625 } 626 n := IPv6len - i 627 for j := i - 1; j >= ellipsis; j-- { 628 ip[j+n] = ip[j] 629 } 630 for j := ellipsis + n - 1; j >= ellipsis; j-- { 631 ip[j] = 0 632 } 633 } else if ellipsis >= 0 { 634 // Ellipsis must represent at least one 0 group. 635 return nil, zone 636 } 637 return ip, zone 638 } 639 640 // ParseIP parses s as an IP address, returning the result. 641 // The string s can be in dotted decimal ("192.0.2.1") 642 // or IPv6 ("2001:db8::68") form. 643 // If s is not a valid textual representation of an IP address, 644 // ParseIP returns nil. 645 func ParseIP(s string) IP { 646 for i := 0; i < len(s); i++ { 647 switch s[i] { 648 case '.': 649 return parseIPv4(s) 650 case ':': 651 ip, _ := parseIPv6(s, false) 652 return ip 653 } 654 } 655 return nil 656 } 657 658 // ParseCIDR parses s as a CIDR notation IP address and prefix length, 659 // like "192.0.2.0/24" or "2001:db8::/32", as defined in 660 // RFC 4632 and RFC 4291. 661 // 662 // It returns the IP address and the network implied by the IP and 663 // prefix length. 664 // For example, ParseCIDR("192.0.2.1/24") returns the IP address 665 // 192.0.2.1 and the network 192.0.2.0/24. 666 func ParseCIDR(s string) (IP, *IPNet, error) { 667 i := byteIndex(s, '/') 668 if i < 0 { 669 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 670 } 671 addr, mask := s[:i], s[i+1:] 672 iplen := IPv4len 673 ip := parseIPv4(addr) 674 if ip == nil { 675 iplen = IPv6len 676 ip, _ = parseIPv6(addr, false) 677 } 678 n, i, ok := dtoi(mask) 679 if ip == nil || !ok || i != len(mask) || n < 0 || n > 8*iplen { 680 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 681 } 682 m := CIDRMask(n, 8*iplen) 683 return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil 684 }