Skip to content

Instantly share code, notes, and snippets.

@jkomyno
Created July 17, 2017 15:27
Show Gist options
  • Save jkomyno/ebf513a6456f5f65196fac5cbea52ead to your computer and use it in GitHub Desktop.
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"
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