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