Skip to content
This repository has been archived by the owner on Mar 29, 2022. It is now read-only.

Commit

Permalink
refactor: improve GetLanIP method.#5
Browse files Browse the repository at this point in the history
  • Loading branch information
Sloaix committed Dec 16, 2019
1 parent d5323a2 commit 880d209
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 26 deletions.
2 changes: 1 addition & 1 deletion build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function afterBuild() {
rm -rf $server_dir/public
gofilog "Build complete. The build product has been exported to the directory $build_dir/output"
cd $build_dir/output
ls -al
du -ah ./
}

beforeBuild
Expand Down
40 changes: 20 additions & 20 deletions gofi-backend/binary/assets.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 33 additions & 5 deletions gofi-backend/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,15 +187,43 @@ func (context *Context) GetLanIP() string {
os.Exit(1)
}


logrus.Infof("print all ip address: %v\n\t", addresses)

for _, address := range addresses {
ipNet, ok := address.(*net.IPNet)

if !ok || ipNet.IP.IsLoopback() || ipNet.IP.To4() == nil {
continue
}

// 检查ip地址判断是否回环地址
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String()
}
// 当前ip属于私有地址,直接返回
if isIpBelongToPrivateIpNet(ipNet.IP) {
return ipNet.IP.To4().String()
}
}

return "127.0.0.1"
}

// 某个ip是否属于私有网段
func isIpBelongToPrivateIpNet(ip net.IP) bool {
for _, ipNet := range getInternalIpNetArray() {
if ipNet.Contains(ip) {
return true
}
}
return false
}

// 返回私有网段切片
func getInternalIpNetArray() []*net.IPNet {
var ipNetArrays []*net.IPNet

for _, ip := range []string{"192.168.0.0/16", "172.16.0.0/12", "10.0.0.0/8"} {
_, ipNet, _ := net.ParseCIDR(ip)
ipNetArrays = append(ipNetArrays, ipNet)
}

return ipNetArrays
}

0 comments on commit 880d209

Please sign in to comment.