github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/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. 344 func (ip IP) MarshalText() ([]byte, error) { 345 if len(ip) == 0 { 346 return []byte(""), nil 347 } 348 if len(ip) != IPv4len && len(ip) != IPv6len { 349 return nil, &AddrError{Err: "invalid IP address", Addr: hexString(ip)} 350 } 351 return []byte(ip.String()), nil 352 } 353 354 // UnmarshalText implements the encoding.TextUnmarshaler interface. 355 // The IP address is expected in a form accepted by ParseIP. 356 func (ip *IP) UnmarshalText(text []byte) error { 357 if len(text) == 0 { 358 *ip = nil 359 return nil 360 } 361 s := string(text) 362 x := ParseIP(s) 363 if x == nil { 364 return &ParseError{Type: "IP address", Text: s} 365 } 366 *ip = x 367 return nil 368 } 369 370 // Equal reports whether ip and x are the same IP address. 371 // An IPv4 address and that same address in IPv6 form are 372 // considered to be equal. 373 func (ip IP) Equal(x IP) bool { 374 if len(ip) == len(x) { 375 return bytesEqual(ip, x) 376 } 377 if len(ip) == IPv4len && len(x) == IPv6len { 378 return bytesEqual(x[0:12], v4InV6Prefix) && bytesEqual(ip, x[12:]) 379 } 380 if len(ip) == IPv6len && len(x) == IPv4len { 381 return bytesEqual(ip[0:12], v4InV6Prefix) && bytesEqual(ip[12:], x) 382 } 383 return false 384 } 385 386 // bytes.Equal is implemented in runtime/asm_$goarch.s 387 //go:linkname bytesEqual bytes.Equal 388 func bytesEqual(x, y []byte) bool 389 390 func (ip IP) matchAddrFamily(x IP) bool { 391 return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil 392 } 393 394 // If mask is a sequence of 1 bits followed by 0 bits, 395 // return the number of 1 bits. 396 func simpleMaskLength(mask IPMask) int { 397 var n int 398 for i, v := range mask { 399 if v == 0xff { 400 n += 8 401 continue 402 } 403 // found non-ff byte 404 // count 1 bits 405 for v&0x80 != 0 { 406 n++ 407 v <<= 1 408 } 409 // rest must be 0 bits 410 if v != 0 { 411 return -1 412 } 413 for i++; i < len(mask); i++ { 414 if mask[i] != 0 { 415 return -1 416 } 417 } 418 break 419 } 420 return n 421 } 422 423 // Size returns the number of leading ones and total bits in the mask. 424 // If the mask is not in the canonical form--ones followed by zeros--then 425 // Size returns 0, 0. 426 func (m IPMask) Size() (ones, bits int) { 427 ones, bits = simpleMaskLength(m), len(m)*8 428 if ones == -1 { 429 return 0, 0 430 } 431 return 432 } 433 434 // String returns the hexadecimal form of m, with no punctuation. 435 func (m IPMask) String() string { 436 if len(m) == 0 { 437 return "<nil>" 438 } 439 return hexString(m) 440 } 441 442 func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) { 443 if ip = n.IP.To4(); ip == nil { 444 ip = n.IP 445 if len(ip) != IPv6len { 446 return nil, nil 447 } 448 } 449 m = n.Mask 450 switch len(m) { 451 case IPv4len: 452 if len(ip) != IPv4len { 453 return nil, nil 454 } 455 case IPv6len: 456 if len(ip) == IPv4len { 457 m = m[12:] 458 } 459 default: 460 return nil, nil 461 } 462 return 463 } 464 465 // Contains reports whether the network includes ip. 466 func (n *IPNet) Contains(ip IP) bool { 467 nn, m := networkNumberAndMask(n) 468 if x := ip.To4(); x != nil { 469 ip = x 470 } 471 l := len(ip) 472 if l != len(nn) { 473 return false 474 } 475 for i := 0; i < l; i++ { 476 if nn[i]&m[i] != ip[i]&m[i] { 477 return false 478 } 479 } 480 return true 481 } 482 483 // Network returns the address's network name, "ip+net". 484 func (n *IPNet) Network() string { return "ip+net" } 485 486 // String returns the CIDR notation of n like "192.0.2.1/24" 487 // or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. 488 // If the mask is not in the canonical form, it returns the 489 // string which consists of an IP address, followed by a slash 490 // character and a mask expressed as hexadecimal form with no 491 // punctuation like "198.51.100.1/c000ff00". 492 func (n *IPNet) String() string { 493 nn, m := networkNumberAndMask(n) 494 if nn == nil || m == nil { 495 return "<nil>" 496 } 497 l := simpleMaskLength(m) 498 if l == -1 { 499 return nn.String() + "/" + m.String() 500 } 501 return nn.String() + "/" + uitoa(uint(l)) 502 } 503 504 // Parse IPv4 address (d.d.d.d). 505 func parseIPv4(s string) IP { 506 var p [IPv4len]byte 507 for i := 0; i < IPv4len; i++ { 508 if len(s) == 0 { 509 // Missing octets. 510 return nil 511 } 512 if i > 0 { 513 if s[0] != '.' { 514 return nil 515 } 516 s = s[1:] 517 } 518 n, c, ok := dtoi(s) 519 if !ok || n > 0xFF { 520 return nil 521 } 522 s = s[c:] 523 p[i] = byte(n) 524 } 525 if len(s) != 0 { 526 return nil 527 } 528 return IPv4(p[0], p[1], p[2], p[3]) 529 } 530 531 // parseIPv6 parses s as a literal IPv6 address described in RFC 4291 532 // and RFC 5952. It can also parse a literal scoped IPv6 address with 533 // zone identifier which is described in RFC 4007 when zoneAllowed is 534 // true. 535 func parseIPv6(s string, zoneAllowed bool) (ip IP, zone string) { 536 ip = make(IP, IPv6len) 537 ellipsis := -1 // position of ellipsis in ip 538 539 if zoneAllowed { 540 s, zone = splitHostZone(s) 541 } 542 543 // Might have leading ellipsis 544 if len(s) >= 2 && s[0] == ':' && s[1] == ':' { 545 ellipsis = 0 546 s = s[2:] 547 // Might be only ellipsis 548 if len(s) == 0 { 549 return ip, zone 550 } 551 } 552 553 // Loop, parsing hex numbers followed by colon. 554 i := 0 555 for i < IPv6len { 556 // Hex number. 557 n, c, ok := xtoi(s) 558 if !ok || n > 0xFFFF { 559 return nil, zone 560 } 561 562 // If followed by dot, might be in trailing IPv4. 563 if c < len(s) && s[c] == '.' { 564 if ellipsis < 0 && i != IPv6len-IPv4len { 565 // Not the right place. 566 return nil, zone 567 } 568 if i+IPv4len > IPv6len { 569 // Not enough room. 570 return nil, zone 571 } 572 ip4 := parseIPv4(s) 573 if ip4 == nil { 574 return nil, zone 575 } 576 ip[i] = ip4[12] 577 ip[i+1] = ip4[13] 578 ip[i+2] = ip4[14] 579 ip[i+3] = ip4[15] 580 s = "" 581 i += IPv4len 582 break 583 } 584 585 // Save this 16-bit chunk. 586 ip[i] = byte(n >> 8) 587 ip[i+1] = byte(n) 588 i += 2 589 590 // Stop at end of string. 591 s = s[c:] 592 if len(s) == 0 { 593 break 594 } 595 596 // Otherwise must be followed by colon and more. 597 if s[0] != ':' || len(s) == 1 { 598 return nil, zone 599 } 600 s = s[1:] 601 602 // Look for ellipsis. 603 if s[0] == ':' { 604 if ellipsis >= 0 { // already have one 605 return nil, zone 606 } 607 ellipsis = i 608 s = s[1:] 609 if len(s) == 0 { // can be at end 610 break 611 } 612 } 613 } 614 615 // Must have used entire string. 616 if len(s) != 0 { 617 return nil, zone 618 } 619 620 // If didn't parse enough, expand ellipsis. 621 if i < IPv6len { 622 if ellipsis < 0 { 623 return nil, zone 624 } 625 n := IPv6len - i 626 for j := i - 1; j >= ellipsis; j-- { 627 ip[j+n] = ip[j] 628 } 629 for j := ellipsis + n - 1; j >= ellipsis; j-- { 630 ip[j] = 0 631 } 632 } else if ellipsis >= 0 { 633 // Ellipsis must represent at least one 0 group. 634 return nil, zone 635 } 636 return ip, zone 637 } 638 639 // ParseIP parses s as an IP address, returning the result. 640 // The string s can be in dotted decimal ("192.0.2.1") 641 // or IPv6 ("2001:db8::68") form. 642 // If s is not a valid textual representation of an IP address, 643 // ParseIP returns nil. 644 func ParseIP(s string) IP { 645 for i := 0; i < len(s); i++ { 646 switch s[i] { 647 case '.': 648 return parseIPv4(s) 649 case ':': 650 ip, _ := parseIPv6(s, false) 651 return ip 652 } 653 } 654 return nil 655 } 656 657 // ParseCIDR parses s as a CIDR notation IP address and prefix length, 658 // like "192.0.2.0/24" or "2001:db8::/32", as defined in 659 // RFC 4632 and RFC 4291. 660 // 661 // It returns the IP address and the network implied by the IP and 662 // prefix length. 663 // For example, ParseCIDR("192.0.2.1/24") returns the IP address 664 // 198.0.2.1 and the network 198.0.2.0/24. 665 func ParseCIDR(s string) (IP, *IPNet, error) { 666 i := byteIndex(s, '/') 667 if i < 0 { 668 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 669 } 670 addr, mask := s[:i], s[i+1:] 671 iplen := IPv4len 672 ip := parseIPv4(addr) 673 if ip == nil { 674 iplen = IPv6len 675 ip, _ = parseIPv6(addr, false) 676 } 677 n, i, ok := dtoi(mask) 678 if ip == nil || !ok || i != len(mask) || n < 0 || n > 8*iplen { 679 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 680 } 681 m := CIDRMask(n, 8*iplen) 682 return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil 683 }