1234567891011121314151617181920212223242526272829303132333435363738 |
- package utils
- import (
- "fmt"
- "net"
- )
- func GetLocalIP() string {
- localIp := "localhost"
- // 获取本机的网络接口信息
- interfaces, err := net.Interfaces()
- if err != nil {
- fmt.Println("无法获取网络接口信息:", err)
- return localIp
- }
- // 遍历每个网络接口,找到第一个非loopback、非IPv6的内网IP地址
- for _, ifAce := range interfaces {
- // 排除loopback接口和IPv6地址
- if ifAce.Flags&net.FlagLoopback == 0 && ifAce.Flags&net.FlagUp != 0 {
- addrs, err := ifAce.Addrs()
- if err != nil {
- fmt.Println("无法获取网络接口地址:", err)
- continue
- }
- for _, addr := range addrs {
- // 检查是否为IPv4地址
- ipNet, ok := addr.(*net.IPNet)
- if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
- // fmt.Println("本机内网IPv4地址:", ipnet.IP.String())
- localIp = ipNet.IP.String()
- return localIp
- }
- }
- }
- }
- return localIp
- }
|