Skip to content

Commit

Permalink
调整:获取IP方式改为,从C类到A类的顺序获取
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Sep 23, 2023
1 parent 322ebb5 commit 39ce63a
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions net/ip.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,43 @@
package net

// 获取本机IP地址
import "net"
import (
"net"
"strings"
)

var ip string
var ips []string
var ipList []string

func GetIp() string {
if ip == "" {
ips, _ = LocalIPv4s()
ip = ips[0]
ipList, _ = LocalIPv4s()
// 优先使用192.168开头
for _, strIp := range ipList {
if strings.HasPrefix(strIp, "192.168.") {
ip = strIp
return ip
}
}

// 使用172.20.开头
for _, strIp := range ipList {
if strings.HasPrefix(strIp, "172.20.") {
ip = strIp
return ip
}
}

// 使用10.开头
for _, strIp := range ipList {
if strings.HasPrefix(strIp, "10.") {
ip = strIp
return ip
}
}

// 没有192.168.x.x和10.x.x.x开头的,只能取第一个IP返回
ip = ipList[0]
}
return ip
}
Expand Down

0 comments on commit 39ce63a

Please sign in to comment.