1 Star 0 Fork 0

brucewang / go公共库

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ip.go 1.29 KB
一键复制 编辑 原始数据 按行查看 历史
brucewang 提交于 2022-01-05 08:08 . 公共库初始化
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 ""
}
Go
1
https://gitee.com/brucewangzhihua1/go-public-library.git
git@gitee.com:brucewangzhihua1/go-public-library.git
brucewangzhihua1
go-public-library
go公共库
v1.0.1

搜索帮助