Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix issue #207: common/utils/net_test.go:25 cannot pass #209

Merged
merged 6 commits into from
Sep 19, 2019
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 60 additions & 19 deletions common/utils/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package utils

import (
"net"
"strings"
)

import (
Expand All @@ -39,46 +40,86 @@ func init() {

// ref: https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go
beiwei30 marked this conversation as resolved.
Show resolved Hide resolved
func GetLocalIP() (string, error) {
ifs, err := net.Interfaces()
faces, err := net.Interfaces()
if err != nil {
return "", perrors.WithStack(err)
}

var ipAddr []byte
for _, i := range ifs {
addrs, err := i.Addrs()
var addr net.IP
for _, face := range faces {
if !isValidNetworkInterface(face) {
continue
}

addrs, err := face.Addrs()
if err != nil {
return "", perrors.WithStack(err)
}
var ip net.IP
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}

if !ip.IsLoopback() && ip.To4() != nil && isPrivateIP(ip.String()) {
ipAddr = ip
break
if ipv4, ok := getValidIPv4(addrs); ok {
addr = ipv4
if isPrivateIP(ipv4) {
return ipv4.String(), nil
}
}
}

if ipAddr == nil {
if addr == nil {
return "", perrors.Errorf("can not get local IP")
}

return net.IP(ipAddr).String(), nil
return addr.String(), nil
}

func isPrivateIP(ipAddr string) bool {
ip := net.ParseIP(ipAddr)
func isPrivateIP(ip net.IP) bool {
for _, priv := range privateBlocks {
if priv.Contains(ip) {
return true
}
}
return false
}

func getValidIPv4(addrs []net.Addr) (net.IP, bool) {
for _, addr := range addrs {
var ip net.IP

switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}

if ip == nil || ip.IsLoopback() {
continue
}

ip = ip.To4()
if ip == nil {
// not an valid ipv4 address
continue
}

return ip, true
}
return nil, false
}

func isValidNetworkInterface(face net.Interface) bool {
if face.Flags&net.FlagUp == 0 {
// interface down
return false
}

if face.Flags&net.FlagLoopback != 0 {
// loopback interface
return false
}

if strings.Contains(strings.ToLower(face.Name), "docker") {
return false
}

return true
}