ip.go 15 KB

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