Created
July 10, 2018 19:16
-
-
Save miguelmota/8544989558d8723b42068aec5bc72ebf to your computer and use it in GitHub Desktop.
Golang get local IP
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
package network | |
import ( | |
"errors" | |
"net" | |
) | |
// LocalIP get the host machine local IP address | |
func LocalIP() (net.IP, error) { | |
ifaces, err := net.Interfaces() | |
if err != nil { | |
return nil, err | |
} | |
for _, i := range ifaces { | |
addrs, err := i.Addrs() | |
if err != nil { | |
return nil, err | |
} | |
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 isPrivateIP(ip) { | |
return ip, nil | |
} | |
} | |
} | |
return nil, errors.New("no IP") | |
} | |
func isPrivateIP(ip net.IP) bool { | |
var privateIPBlocks []*net.IPNet | |
for _, cidr := range []string{ | |
// don't check loopback ips | |
//"127.0.0.0/8", // IPv4 loopback | |
//"::1/128", // IPv6 loopback | |
//"fe80::/10", // IPv6 link-local | |
"10.0.0.0/8", // RFC1918 | |
"172.16.0.0/12", // RFC1918 | |
"192.168.0.0/16", // RFC1918 | |
} { | |
_, block, _ := net.ParseCIDR(cidr) | |
privateIPBlocks = append(privateIPBlocks, block) | |
} | |
for _, block := range privateIPBlocks { | |
if block.Contains(ip) { | |
return true | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much, my guy. Thank you oh so very much.