ip.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package pkg
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net"
  8. "net/http"
  9. )
  10. // 获取外网ip地址
  11. func GetLocation(ip, key string) string {
  12. if ip == "127.0.0.1" || ip == "localhost" {
  13. return "内部IP"
  14. }
  15. // 若用户不填写IP,则取客户HTTP之中的请求来进行定位
  16. url := "https://restapi.amap.com/v3/ip?key=" + key
  17. log.Println("restapi.amap.com url", url)
  18. resp, err := http.Get(url)
  19. if err != nil {
  20. log.Println("restapi.amap.com failed:", err)
  21. return "未知位置"
  22. }
  23. defer resp.Body.Close()
  24. s, err := ioutil.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. log.Println("Umarshal failed:", err)
  30. }
  31. return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
  32. }
  33. // 获取局域网ip地址
  34. func GetLocalHost() string {
  35. netInterfaces, err := net.Interfaces()
  36. if err != nil {
  37. log.Println("net.Interfaces failed, err:", err.Error())
  38. }
  39. for i := 0; i < len(netInterfaces); i++ {
  40. if (netInterfaces[i].Flags & net.FlagUp) != 0 {
  41. addrs, _ := netInterfaces[i].Addrs()
  42. for _, address := range addrs {
  43. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  44. if ipnet.IP.To4() != nil {
  45. return ipnet.IP.String()
  46. }
  47. }
  48. }
  49. }
  50. }
  51. return ""
  52. }