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

1 year ago
package goip
import (
10 months ago
"context"
1 year ago
"encoding/json"
11 months ago
"go.dtapp.net/gorequest"
9 months ago
"log"
1 year ago
"net"
)
// GetInsideIp 内网ip
10 months ago
func GetInsideIp(ctx context.Context) string {
9 months ago
1 year 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
10 months ago
func Ips(ctx context.Context) (map[string]string, error) {
1 year 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
9 months ago
func GetOutsideIp(ctx context.Context) string {
9 months ago
// 返回结果
type respGetOutsideIp struct {
Data struct {
Ip string `json:"ip,omitempty"`
} `json:"data"`
}
9 months ago
// 请求
getHttp := gorequest.NewHttp()
getHttp.SetUri("https://api.dtapp.net/ip")
response, err := getHttp.Get(ctx)
1 year ago
if err != nil {
9 months ago
log.Printf("[GetOutsideIp]getHttp.Get%s\n", err)
9 months ago
return "0.0.0.0"
1 year ago
}
9 months ago
// 解析
9 months ago
var responseJson respGetOutsideIp
err = json.Unmarshal(response.ResponseBody, &responseJson)
1 year ago
if err != nil {
9 months ago
log.Printf("[GetOutsideIp]json.Unmarshal%s\n", err)
9 months ago
return "0.0.0.0"
1 year ago
}
9 months ago
if responseJson.Data.Ip == "" {
responseJson.Data.Ip = "0.0.0.0"
}
return responseJson.Data.Ip
1 year ago
}
1 year ago
// GetMacAddr 获取Mac地址
10 months ago
func GetMacAddr(ctx context.Context) (arrays []string) {
1 year 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
}