| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package pkg
- import (
- "encoding/json"
- "fmt"
- "io"
- "net"
- "net/http"
- )
- // GetLocation 获取外网ip地址
- func GetLocation(ip, key string) string {
- if ip == "127.0.0.1" || ip == "localhost" || ip == "::1" {
- return "内部IP"
- }
- url := "https://restapi.amap.com/v5/ip?ip=" + ip + "&type=4&key=" + key
- fmt.Println("url", url)
- resp, err := http.Get(url)
- if err != nil {
- fmt.Println("restapi.AmAp.com failed:", err)
- return "未知位置"
- }
- defer func(Body io.ReadCloser) {
- _ = Body.Close()
- }(resp.Body)
- s, err := io.ReadAll(resp.Body)
- fmt.Println(string(s))
- m := make(map[string]string)
- err = json.Unmarshal(s, &m)
- if err != nil {
- fmt.Println("UnMarshal failed:", err)
- }
- //if m["province"] == "" {
- // return "未知位置"
- //}
- return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
- }
- // GetLocalHost 获取局域网ip地址
- func GetLocalHost() string {
- netInterfaces, err := net.Interfaces()
- if err != nil {
- fmt.Println("net.Interfaces failed, err:", err.Error())
- }
- for i := 0; i < len(netInterfaces); i++ {
- if (netInterfaces[i].Flags & net.FlagUp) != 0 {
- addrList, _ := netInterfaces[i].Addrs()
- for _, address := range addrList {
- if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
- if ipnet.IP.To4() != nil {
- return ipnet.IP.String()
- }
- }
- }
- }
- }
- return ""
- }
|