ip.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package host
  2. import (
  3. "net"
  4. "os"
  5. "git.giaever.org/joachimmg/go-log.git/log"
  6. "git.giaever.org/joachimmg/m-dns/errors"
  7. )
  8. type IPvType int
  9. const (
  10. IPv4 IPvType = iota << 1
  11. IPv6 IPvType = iota << 1
  12. NoIP IPvType = iota << 1
  13. )
  14. type HostIP interface {
  15. String() string
  16. Type() (net.IP, IPvType)
  17. AsIP() net.IP
  18. }
  19. type IP net.IP
  20. func (i IP) String() string {
  21. return i.AsIP().String()
  22. }
  23. func (i IP) AsIP() net.IP {
  24. return net.IP(i)
  25. }
  26. func (i IP) Type() (net.IP, IPvType) {
  27. if ip := i.AsIP().To4(); ip != nil {
  28. switch ip.String() {
  29. case "127.0.0.1",
  30. net.IPv4zero.String(),
  31. net.IPv4bcast.String(),
  32. net.IPv4allsys.String(),
  33. net.IPv4allrouter.String():
  34. return nil, NoIP
  35. default:
  36. return ip, IPv4
  37. }
  38. }
  39. if ip := i.AsIP().To16(); ip != nil {
  40. switch ip.String() {
  41. case net.IPv6zero.String(),
  42. net.IPv6loopback.String(),
  43. net.IPv6unspecified.String(),
  44. net.IPv6linklocalallnodes.String(),
  45. net.IPv6linklocalallrouters.String(),
  46. net.IPv6interfacelocalallnodes.String():
  47. return nil, NoIP
  48. default:
  49. return ip, IPv6
  50. }
  51. }
  52. return nil, NoIP
  53. }
  54. func (i IP) validForHostname(hn HostString) (IP, error) {
  55. log.Traceln(errors.HostIP, i, hn)
  56. if _, t := i.Type(); t == NoIP {
  57. log.Traceln(errors.HostIP, errors.HostIPIsInvalid)
  58. return nil, errors.HostIPIsInvalid
  59. }
  60. f := false
  61. if lhn, _ := os.Hostname(); lhn == hn.String() {
  62. addrs, err := net.InterfaceAddrs()
  63. if err != nil {
  64. log.Traceln(errors.HostIP, err)
  65. return nil, err
  66. }
  67. for _, addr := range addrs {
  68. if addr.(*net.IPNet).Contains(i.AsIP()) {
  69. f = true
  70. break
  71. }
  72. }
  73. } else {
  74. addrs, err := net.LookupIP(hn.String())
  75. if err != nil {
  76. log.Traceln(errors.HostIP, err)
  77. return nil, err
  78. }
  79. for _, addr := range addrs {
  80. if addr.String() == i.String() {
  81. f = true
  82. }
  83. }
  84. }
  85. if f == false {
  86. log.Traceln(errors.HostIP, errors.HostIPIsInvalid)
  87. return nil, errors.HostIPIsInvalid
  88. }
  89. return i, nil
  90. }