添加函数GetLocalIP
This commit is contained in:
parent
85a82957ca
commit
73c047e43f
33
local_ip.go
Normal file
33
local_ip.go
Normal file
@ -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地址")
|
||||
}
|
15
local_ip_test.go
Normal file
15
local_ip_test.go
Normal file
@ -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)
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user