forked from go-admin-team/go-admin-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
61 lines (53 loc) · 1.29 KB
/
ip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package pkg
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
)
// 获取外网ip地址
func GetLocation(ip, key string) string {
if ip == "127.0.0.1" || ip == "localhost" {
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 resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(s))
m := make(map[string]string)
err = json.Unmarshal(s, &m)
if err != nil {
fmt.Println("Umarshal failed:", err)
}
//if m["province"] == "" {
// return "未知位置"
//}
return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
}
// 获取局域网ip地址
func GetLocaHonst() 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 {
addrs, _ := netInterfaces[i].Addrs()
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
}
}
return ""
}