netaddr.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package netaddr is a transitional package while we finish migrating from inet.af/netaddr
  4. // to Go 1.18's net/netip.
  5. //
  6. // TODO(bradfitz): delete this package eventually. Tracking bug is
  7. // https://github.com/tailscale/tailscale/issues/5162
  8. package netaddr
  9. import (
  10. "net"
  11. "net/netip"
  12. )
  13. // IPv4 returns the IP of the IPv4 address a.b.c.d.
  14. func IPv4(a, b, c, d uint8) netip.Addr {
  15. return netip.AddrFrom4([4]byte{a, b, c, d})
  16. }
  17. // Unmap returns the provided AddrPort with its Addr IP component Unmap'ed.
  18. //
  19. // See https://github.com/golang/go/issues/53607#issuecomment-1203466984
  20. func Unmap(ap netip.AddrPort) netip.AddrPort {
  21. return netip.AddrPortFrom(ap.Addr().Unmap(), ap.Port())
  22. }
  23. // FromStdIPNet returns an IPPrefix from the standard library's IPNet type.
  24. // If std is invalid, ok is false.
  25. func FromStdIPNet(std *net.IPNet) (prefix netip.Prefix, ok bool) {
  26. ip, ok := netip.AddrFromSlice(std.IP)
  27. if !ok {
  28. return netip.Prefix{}, false
  29. }
  30. ip = ip.Unmap()
  31. if ln := len(std.Mask); ln != net.IPv4len && ln != net.IPv6len {
  32. // Invalid mask.
  33. return netip.Prefix{}, false
  34. }
  35. ones, bits := std.Mask.Size()
  36. if ones == 0 && bits == 0 {
  37. // IPPrefix does not support non-contiguous masks.
  38. return netip.Prefix{}, false
  39. }
  40. return netip.PrefixFrom(ip, ones), true
  41. }