Created
July 17, 2017 15:27
-
-
Save jkomyno/ebf513a6456f5f65196fac5cbea52ead to your computer and use it in GitHub Desktop.
Get local IP with short subnet mask notation, example: "192.168.252.129/24"
This file contains hidden or 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 main | |
import ( | |
"fmt" | |
"net" | |
"os" | |
) | |
func getIPWithMask() string { | |
addrs, err := net.InterfaceAddrs() | |
if err != nil { | |
os.Stderr.WriteString("Oops: " + err.Error() + "\n") | |
os.Exit(1) | |
} | |
for _, a := range addrs { | |
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { | |
if ipnet.IP.To4() != nil { | |
return ipnet.String() | |
} | |
} | |
} | |
return "" | |
} | |
func main() { | |
fmt.Println(getIPWithMask()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment