ip.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package ip_helper
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
  7. )
  8. func IsIPv4(address string) bool {
  9. return strings.Count(address, ":") < 2
  10. }
  11. func IsIPv6(address string) bool {
  12. return strings.Count(address, ":") >= 2
  13. }
  14. // 获取外网ip
  15. func GetExternalIPV4() string {
  16. return httper2.Get("https://api.ipify.org", nil)
  17. }
  18. // 获取外网ip
  19. func GetExternalIPV6() string {
  20. return httper2.Get("https://api6.ipify.org", nil)
  21. }
  22. // 获取本地ip
  23. func GetLoclIp() string {
  24. addrs, err := net.InterfaceAddrs()
  25. if err != nil {
  26. return "127.0.0.1"
  27. }
  28. for _, address := range addrs {
  29. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  30. if ipnet.IP.To4() != nil {
  31. return ipnet.IP.String()
  32. }
  33. }
  34. }
  35. return "127.0.0.1"
  36. }
  37. func GetDeviceAllIP(port string) []string {
  38. var address []string
  39. addrs, err := net.InterfaceAddrs()
  40. if err != nil {
  41. return address
  42. }
  43. for _, a := range addrs {
  44. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
  45. if ipNet.IP.To16() != nil {
  46. address = append(address, ipNet.IP.String()+":"+port)
  47. }
  48. }
  49. }
  50. return address
  51. }
  52. func GetDeviceAllIPv4() map[string]string {
  53. address := make(map[string]string)
  54. addrs, err := net.Interfaces()
  55. if err != nil {
  56. return address
  57. }
  58. for _, a := range addrs {
  59. if a.Flags&net.FlagLoopback != 0 || a.Flags&net.FlagUp == 0 {
  60. continue
  61. }
  62. addrs, err := a.Addrs()
  63. if err != nil {
  64. fmt.Println("Error:", err)
  65. continue
  66. }
  67. for _, addr := range addrs {
  68. if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
  69. address[a.Name] = ipnet.IP.String()
  70. }
  71. }
  72. }
  73. return address
  74. }
  75. func HasLocalIP(ip net.IP) bool {
  76. if ip.IsLoopback() {
  77. return true
  78. }
  79. ip4 := ip.To4()
  80. if ip4 == nil {
  81. return false
  82. }
  83. return ip4[0] == 10 || // 10.0.0.0/8
  84. (ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12
  85. (ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16
  86. (ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16
  87. }