github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/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 // If the address is an IPv4 address, the string representation 256 // is dotted decimal ("74.125.19.99"). Otherwise the representation 257 // is IPv6 ("2001:4860:0:2001::68"). 258 func (ip IP) String() string { 259 p := ip 260 261 if len(ip) == 0 { 262 return "<nil>" 263 } 264 265 // If IPv4, use dotted notation. 266 if p4 := p.To4(); len(p4) == IPv4len { 267 return uitoa(uint(p4[0])) + "." + 268 uitoa(uint(p4[1])) + "." + 269 uitoa(uint(p4[2])) + "." + 270 uitoa(uint(p4[3])) 271 } 272 if len(p) != IPv6len { 273 return "?" 274 } 275 276 // Find longest run of zeros. 277 e0 := -1 278 e1 := -1 279 for i := 0; i < IPv6len; i += 2 { 280 j := i 281 for j < IPv6len && p[j] == 0 && p[j+1] == 0 { 282 j += 2 283 } 284 if j > i && j-i > e1-e0 { 285 e0 = i 286 e1 = j 287 i = j 288 } 289 } 290 // The symbol "::" MUST NOT be used to shorten just one 16 bit 0 field. 291 if e1-e0 <= 2 { 292 e0 = -1 293 e1 = -1 294 } 295 296 const maxLen = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") 297 b := make([]byte, 0, maxLen) 298 299 // Print with possible :: in place of run of zeros 300 for i := 0; i < IPv6len; i += 2 { 301 if i == e0 { 302 b = append(b, ':', ':') 303 i = e1 304 if i >= IPv6len { 305 break 306 } 307 } else if i > 0 { 308 b = append(b, ':') 309 } 310 b = appendHex(b, (uint32(p[i])<<8)|uint32(p[i+1])) 311 } 312 return string(b) 313 } 314 315 // ipEmptyString is like ip.String except that it returns 316 // an empty string when ip is unset. 317 func ipEmptyString(ip IP) string { 318 if len(ip) == 0 { 319 return "" 320 } 321 return ip.String() 322 } 323 324 // MarshalText implements the encoding.TextMarshaler interface. 325 // The encoding is the same as returned by String. 326 func (ip IP) MarshalText() ([]byte, error) { 327 if len(ip) == 0 { 328 return []byte(""), nil 329 } 330 if len(ip) != IPv4len && len(ip) != IPv6len { 331 return nil, &AddrError{Err: "invalid IP address", Addr: ip.String()} 332 } 333 return []byte(ip.String()), nil 334 } 335 336 // UnmarshalText implements the encoding.TextUnmarshaler interface. 337 // The IP address is expected in a form accepted by ParseIP. 338 func (ip *IP) UnmarshalText(text []byte) error { 339 if len(text) == 0 { 340 *ip = nil 341 return nil 342 } 343 s := string(text) 344 x := ParseIP(s) 345 if x == nil { 346 return &ParseError{Type: "IP address", Text: s} 347 } 348 *ip = x 349 return nil 350 } 351 352 // Equal reports whether ip and x are the same IP address. 353 // An IPv4 address and that same address in IPv6 form are 354 // considered to be equal. 355 func (ip IP) Equal(x IP) bool { 356 if len(ip) == len(x) { 357 return bytesEqual(ip, x) 358 } 359 if len(ip) == IPv4len && len(x) == IPv6len { 360 return bytesEqual(x[0:12], v4InV6Prefix) && bytesEqual(ip, x[12:]) 361 } 362 if len(ip) == IPv6len && len(x) == IPv4len { 363 return bytesEqual(ip[0:12], v4InV6Prefix) && bytesEqual(ip[12:], x) 364 } 365 return false 366 } 367 368 func bytesEqual(x, y []byte) bool { 369 if len(x) != len(y) { 370 return false 371 } 372 for i, b := range x { 373 if y[i] != b { 374 return false 375 } 376 } 377 return true 378 } 379 380 func (ip IP) matchAddrFamily(x IP) bool { 381 return ip.To4() != nil && x.To4() != nil || ip.To16() != nil && ip.To4() == nil && x.To16() != nil && x.To4() == nil 382 } 383 384 // If mask is a sequence of 1 bits followed by 0 bits, 385 // return the number of 1 bits. 386 func simpleMaskLength(mask IPMask) int { 387 var n int 388 for i, v := range mask { 389 if v == 0xff { 390 n += 8 391 continue 392 } 393 // found non-ff byte 394 // count 1 bits 395 for v&0x80 != 0 { 396 n++ 397 v <<= 1 398 } 399 // rest must be 0 bits 400 if v != 0 { 401 return -1 402 } 403 for i++; i < len(mask); i++ { 404 if mask[i] != 0 { 405 return -1 406 } 407 } 408 break 409 } 410 return n 411 } 412 413 // Size returns the number of leading ones and total bits in the mask. 414 // If the mask is not in the canonical form--ones followed by zeros--then 415 // Size returns 0, 0. 416 func (m IPMask) Size() (ones, bits int) { 417 ones, bits = simpleMaskLength(m), len(m)*8 418 if ones == -1 { 419 return 0, 0 420 } 421 return 422 } 423 424 // String returns the hexadecimal form of m, with no punctuation. 425 func (m IPMask) String() string { 426 if len(m) == 0 { 427 return "<nil>" 428 } 429 buf := make([]byte, len(m)*2) 430 for i, b := range m { 431 buf[i*2], buf[i*2+1] = hexDigit[b>>4], hexDigit[b&0xf] 432 } 433 return string(buf) 434 } 435 436 func networkNumberAndMask(n *IPNet) (ip IP, m IPMask) { 437 if ip = n.IP.To4(); ip == nil { 438 ip = n.IP 439 if len(ip) != IPv6len { 440 return nil, nil 441 } 442 } 443 m = n.Mask 444 switch len(m) { 445 case IPv4len: 446 if len(ip) != IPv4len { 447 return nil, nil 448 } 449 case IPv6len: 450 if len(ip) == IPv4len { 451 m = m[12:] 452 } 453 default: 454 return nil, nil 455 } 456 return 457 } 458 459 // Contains reports whether the network includes ip. 460 func (n *IPNet) Contains(ip IP) bool { 461 nn, m := networkNumberAndMask(n) 462 if x := ip.To4(); x != nil { 463 ip = x 464 } 465 l := len(ip) 466 if l != len(nn) { 467 return false 468 } 469 for i := 0; i < l; i++ { 470 if nn[i]&m[i] != ip[i]&m[i] { 471 return false 472 } 473 } 474 return true 475 } 476 477 // Network returns the address's network name, "ip+net". 478 func (n *IPNet) Network() string { return "ip+net" } 479 480 // String returns the CIDR notation of n like "192.168.100.1/24" 481 // or "2001:DB8::/48" as defined in RFC 4632 and RFC 4291. 482 // If the mask is not in the canonical form, it returns the 483 // string which consists of an IP address, followed by a slash 484 // character and a mask expressed as hexadecimal form with no 485 // punctuation like "192.168.100.1/c000ff00". 486 func (n *IPNet) String() string { 487 nn, m := networkNumberAndMask(n) 488 if nn == nil || m == nil { 489 return "<nil>" 490 } 491 l := simpleMaskLength(m) 492 if l == -1 { 493 return nn.String() + "/" + m.String() 494 } 495 return nn.String() + "/" + uitoa(uint(l)) 496 } 497 498 // Parse IPv4 address (d.d.d.d). 499 func parseIPv4(s string) IP { 500 var p [IPv4len]byte 501 i := 0 502 for j := 0; j < IPv4len; j++ { 503 if i >= len(s) { 504 // Missing octets. 505 return nil 506 } 507 if j > 0 { 508 if s[i] != '.' { 509 return nil 510 } 511 i++ 512 } 513 var ( 514 n int 515 ok bool 516 ) 517 n, i, ok = dtoi(s, i) 518 if !ok || n > 0xFF { 519 return nil 520 } 521 p[j] = byte(n) 522 } 523 if i != len(s) { 524 return nil 525 } 526 return IPv4(p[0], p[1], p[2], p[3]) 527 } 528 529 // parseIPv6 parses s as a literal IPv6 address described in RFC 4291 530 // and RFC 5952. It can also parse a literal scoped IPv6 address with 531 // zone identifier which is described in RFC 4007 when zoneAllowed is 532 // true. 533 func parseIPv6(s string, zoneAllowed bool) (ip IP, zone string) { 534 ip = make(IP, IPv6len) 535 ellipsis := -1 // position of ellipsis in p 536 i := 0 // index in string s 537 538 if zoneAllowed { 539 s, zone = splitHostZone(s) 540 } 541 542 // Might have leading ellipsis 543 if len(s) >= 2 && s[0] == ':' && s[1] == ':' { 544 ellipsis = 0 545 i = 2 546 // Might be only ellipsis 547 if i == len(s) { 548 return ip, zone 549 } 550 } 551 552 // Loop, parsing hex numbers followed by colon. 553 j := 0 554 for j < IPv6len { 555 // Hex number. 556 n, i1, ok := xtoi(s, i) 557 if !ok || n > 0xFFFF { 558 return nil, zone 559 } 560 561 // If followed by dot, might be in trailing IPv4. 562 if i1 < len(s) && s[i1] == '.' { 563 if ellipsis < 0 && j != IPv6len-IPv4len { 564 // Not the right place. 565 return nil, zone 566 } 567 if j+IPv4len > IPv6len { 568 // Not enough room. 569 return nil, zone 570 } 571 ip4 := parseIPv4(s[i:]) 572 if ip4 == nil { 573 return nil, zone 574 } 575 ip[j] = ip4[12] 576 ip[j+1] = ip4[13] 577 ip[j+2] = ip4[14] 578 ip[j+3] = ip4[15] 579 i = len(s) 580 j += IPv4len 581 break 582 } 583 584 // Save this 16-bit chunk. 585 ip[j] = byte(n >> 8) 586 ip[j+1] = byte(n) 587 j += 2 588 589 // Stop at end of string. 590 i = i1 591 if i == len(s) { 592 break 593 } 594 595 // Otherwise must be followed by colon and more. 596 if s[i] != ':' || i+1 == len(s) { 597 return nil, zone 598 } 599 i++ 600 601 // Look for ellipsis. 602 if s[i] == ':' { 603 if ellipsis >= 0 { // already have one 604 return nil, zone 605 } 606 ellipsis = j 607 if i++; i == len(s) { // can be at end 608 break 609 } 610 } 611 } 612 613 // Must have used entire string. 614 if i != len(s) { 615 return nil, zone 616 } 617 618 // If didn't parse enough, expand ellipsis. 619 if j < IPv6len { 620 if ellipsis < 0 { 621 return nil, zone 622 } 623 n := IPv6len - j 624 for k := j - 1; k >= ellipsis; k-- { 625 ip[k+n] = ip[k] 626 } 627 for k := ellipsis + n - 1; k >= ellipsis; k-- { 628 ip[k] = 0 629 } 630 } else if ellipsis >= 0 { 631 // Ellipsis must represent at least one 0 group. 632 return nil, zone 633 } 634 return ip, zone 635 } 636 637 // ParseIP parses s as an IP address, returning the result. 638 // The string s can be in dotted decimal ("74.125.19.99") 639 // or IPv6 ("2001:4860:0:2001::68") form. 640 // If s is not a valid textual representation of an IP address, 641 // ParseIP returns nil. 642 func ParseIP(s string) IP { 643 for i := 0; i < len(s); i++ { 644 switch s[i] { 645 case '.': 646 return parseIPv4(s) 647 case ':': 648 ip, _ := parseIPv6(s, false) 649 return ip 650 } 651 } 652 return nil 653 } 654 655 // ParseCIDR parses s as a CIDR notation IP address and mask, 656 // like "192.168.100.1/24" or "2001:DB8::/48", as defined in 657 // RFC 4632 and RFC 4291. 658 // 659 // It returns the IP address and the network implied by the IP 660 // and mask. For example, ParseCIDR("192.168.100.1/16") returns 661 // the IP address 192.168.100.1 and the network 192.168.0.0/16. 662 func ParseCIDR(s string) (IP, *IPNet, error) { 663 i := byteIndex(s, '/') 664 if i < 0 { 665 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 666 } 667 addr, mask := s[:i], s[i+1:] 668 iplen := IPv4len 669 ip := parseIPv4(addr) 670 if ip == nil { 671 iplen = IPv6len 672 ip, _ = parseIPv6(addr, false) 673 } 674 n, i, ok := dtoi(mask, 0) 675 if ip == nil || !ok || i != len(mask) || n < 0 || n > 8*iplen { 676 return nil, nil, &ParseError{Type: "CIDR address", Text: s} 677 } 678 m := CIDRMask(n, 8*iplen) 679 return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil 680 }