ip.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package pkg
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. )
  9. // GetLocation 获取外网ip地址
  10. func GetLocation(ip, key string) string {
  11. if ip == "127.0.0.1" || ip == "localhost" || ip == "::1" {
  12. return "内部IP"
  13. }
  14. url := "https://restapi.amap.com/v5/ip?ip=" + ip + "&type=4&key=" + key
  15. fmt.Println("url", url)
  16. resp, err := http.Get(url)
  17. if err != nil {
  18. fmt.Println("restapi.AmAp.com failed:", err)
  19. return "未知位置"
  20. }
  21. defer func(Body io.ReadCloser) {
  22. _ = Body.Close()
  23. }(resp.Body)
  24. s, err := io.ReadAll(resp.Body)
  25. fmt.Println(string(s))
  26. m := make(map[string]string)
  27. err = json.Unmarshal(s, &m)
  28. if err != nil {
  29. fmt.Println("UnMarshal failed:", err)
  30. }
  31. //if m["province"] == "" {
  32. // return "未知位置"
  33. //}
  34. return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
  35. }
  36. // GetLocalHost 获取局域网ip地址
  37. func GetLocalHost() string {
  38. netInterfaces, err := net.Interfaces()
  39. if err != nil {
  40. fmt.Println("net.Interfaces failed, err:", err.Error())
  41. }
  42. for i := 0; i < len(netInterfaces); i++ {
  43. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  44. addrList, _ := netInterfaces[i].Addrs()
  45. for _, address := range addrList {
  46. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  47. if ipnet.IP.To4() != nil {
  48. return ipnet.IP.String()
  49. }
  50. }
  51. }
  52. }
  53. }
  54. return ""
  55. }