From 73c047e43f079c5e1254731e1a35b3c44347b78f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AE=B7=E5=8B=87?= Date: Thu, 10 Aug 2023 14:48:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=87=BD=E6=95=B0GetLocalIP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- local_ip.go | 33 +++++++++++++++++++++++++++++++++ local_ip_test.go | 15 +++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 local_ip.go create mode 100644 local_ip_test.go diff --git a/local_ip.go b/local_ip.go new file mode 100644 index 0000000..aa84660 --- /dev/null +++ b/local_ip.go @@ -0,0 +1,33 @@ +package q5 + +import ( + "fmt" + "net" +) + +func GetLocalIP() (string, error) { + interfaces, err := net.Interfaces() + if err != nil { + return "", err + } + for _, iface := range interfaces { + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + addrs, err := iface.Addrs() + if err != nil { + return "", err + } + for _, addr := range addrs { + ipnet, ok := addr.(*net.IPNet) + if !ok || ipnet.IP.IsLoopback() { + continue + } + if ipnet.IP.To4() != nil { + return ipnet.IP.String(), nil + } + } + } + + return "", fmt.Errorf("无法获取本机有效的IP地址") +} diff --git a/local_ip_test.go b/local_ip_test.go new file mode 100644 index 0000000..c4e5ca3 --- /dev/null +++ b/local_ip_test.go @@ -0,0 +1,15 @@ +package q5 + +import ( + "fmt" + "testing" +) + +func TestGetLocalIP(t *testing.T) { + ip, err := GetLocalIP() + if err != nil { + // 错误处理 + t.Errorf("local ip %v error:%s", ip, err) + } + fmt.Printf("local ip:[%s]\n", ip) +}