Skip to content

Instantly share code, notes, and snippets.

@leafsummer
Last active May 6, 2019 11:02
Show Gist options
  • Save leafsummer/8349431efa25ee83b7eb4dd5395db63e to your computer and use it in GitHub Desktop.
Save leafsummer/8349431efa25ee83b7eb4dd5395db63e to your computer and use it in GitHub Desktop.
[get local ip with golang]
package main
import (
"net"
"fmt"
)
func GetLocalIP() (ipv4 string, err error) {
var (
addrs []net.Addr
addr net.Addr
ipNet *net.IPNet
ok bool
)
if addrs, err = net.InterfaceAddrs(); err != nil {
return
}
//get the netcard except lo
for _, addr = range addrs {
//type assert
if ipNet, ok = addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ipv4 = ipNet.IP.String()
return
}
}
}
return
}
func main() {
var (
local_ip string
err error
)
if local_ip, err = GetLocalIP(); err != nil {
return
}
fmt.Println("Local IP is %s", local_ip)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment