源码
package main
import (
"fmt"
"net"
"strings"
"gitee.com/liumou_site/logger"
"github.com/spf13/cast"
)
// GetUseIP 通过Udp协议发送请求获取正在使用的IP(默认路由IP,如果做了自定义路由并且设置了目标服务器,则会获取到对应的本地IP)
func GetUseIP() (string, error) {
dnsList := []string{"119.29.29.29", "114.114.114.114"}
for _, dns := range dnsList {
server := string(dns) + ":" + cast.ToString("53")
logger.Debug("Server: ", server)
conn, err := net.Dial("udp", server)
// 获取本地IP
if err != nil {
// 延迟函数
defer func(conn net.Conn) {
err := conn.Close()
if err != nil {
return
}
}(conn)
logger.Error("获取失败,请检查网络是否正常连接网络: ", err)
if dns == "114.114.114.114" {
return "failed", err
}
} else {
LocalIpInfo := conn.LocalAddr().String()
// 获取:号的index值,然后截取
LocalIp := strings.LastIndex(LocalIpInfo, ":")
logger.Debug("本地请求信息: ", LocalIpInfo)
logger.Debug(":号索引值: ", LocalIp)
return LocalIpInfo[0:LocalIp], nil
}
}
return "failed", fmt.Errorf("获取异常")
}
func main() {
ip, err := GetUseIP()
if err == nil {
logger.Info("获取成功: ", ip)
} else {
logger.Error("获取失败: ", err.Error())
}
}
效果
[Running] go run "d:\data\git\Go\测试\main.go"
[2022-12-30 16:30:39] [DEBG] [main.go:17] Server: 119.29.29.29:53
[2022-12-30 16:30:40] [DEBG] [main.go:36] 本地请求信息: 10.1.1.90:58825
[2022-12-30 16:30:40] [DEBG] [main.go:37] :号索引值: 9
[2022-12-30 16:30:40] [INFO] [main.go:47] 获取成功: 10.1.1.90