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