ip.go 1.1 KB

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