You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
goip/ip.go

99 lines
2.0 KiB

2 years ago
package goip
import (
2 years ago
"context"
2 years ago
"encoding/json"
2 years ago
"go.dtapp.net/gorequest"
2 years ago
"log"
2 years ago
"net"
)
// GetInsideIp 内网ip
2 years ago
func GetInsideIp(ctx context.Context) string {
2 years ago
2 years ago
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
panic(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP.String()
}
// Ips 获取全部网卡的全部IP
2 years ago
func Ips(ctx context.Context) (map[string]string, error) {
2 years ago
ips := make(map[string]string)
//返回 interface 结构体对象的列表,包含了全部网卡信息
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
//遍历全部网卡
for _, i := range interfaces {
// Addrs() 方法返回一个网卡上全部的IP列表
address, err := i.Addrs()
if err != nil {
return nil, err
}
//遍历一个网卡上全部的IP列表组合为一个字符串放入对应网卡名称的map中
for _, v := range address {
ips[i.Name] += v.String() + " "
}
}
return ips, nil
}
// GetOutsideIp 外网ip
2 years ago
func GetOutsideIp(ctx context.Context) string {
2 years ago
// 返回结果
type respGetOutsideIp struct {
Data struct {
Ip string `json:"ip,omitempty"`
} `json:"data"`
}
2 years ago
// 请求
getHttp := gorequest.NewHttp()
getHttp.SetUri("https://api.dtapp.net/ip")
response, err := getHttp.Get(ctx)
2 years ago
if err != nil {
2 years ago
log.Printf("[GetOutsideIp]getHttp.Get%s\n", err)
2 years ago
return "0.0.0.0"
2 years ago
}
2 years ago
// 解析
2 years ago
var responseJson respGetOutsideIp
err = json.Unmarshal(response.ResponseBody, &responseJson)
2 years ago
if err != nil {
2 years ago
log.Printf("[GetOutsideIp]json.Unmarshal%s\n", err)
2 years ago
return "0.0.0.0"
2 years ago
}
2 years ago
if responseJson.Data.Ip == "" {
responseJson.Data.Ip = "0.0.0.0"
}
return responseJson.Data.Ip
2 years ago
}
2 years ago
// GetMacAddr 获取Mac地址
2 years ago
func GetMacAddr(ctx context.Context) (arrays []string) {
2 years ago
netInterfaces, err := net.Interfaces()
if err != nil {
return arrays
}
for _, netInterface := range netInterfaces {
addr := netInterface.HardwareAddr.String()
if len(addr) == 0 {
continue
}
arrays = append(arrays, addr)
}
return arrays
}