Created
February 9, 2018 07:43
-
-
Save zxh/b3ff8d94578a0332f5b4e6b50a8398d7 to your computer and use it in GitHub Desktop.
golang get ip address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getIp() (net.IP, error) { | |
interfaces, e := net.Interfaces() | |
if e != nil { | |
return nil, errors.New("get Interfaces error") | |
} | |
for _, i := range interfaces { | |
// the flags value maybe 'pointtopoint', it also has a ip, filter it. | |
if !strings.Contains(i.Flags.String(), "broadcast") { | |
continue | |
} | |
addresses, e := i.Addrs() | |
if e != nil { | |
return nil, errors.New("get addresses failed") | |
} | |
for _, add := range addresses { | |
var ip net.IP | |
switch t := add.(type) { | |
case *net.IPNet: | |
ip = t.IP | |
case *net.IPAddr: | |
ip = t.IP | |
} | |
// filter loopback ip | |
if !ip.IsLoopback() && ip.To4() != nil { | |
// return the first occurrence ip | |
return ip, nil | |
} | |
} | |
} | |
return nil, errors.New("find none ip") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment