Last active
May 6, 2019 11:02
-
-
Save leafsummer/8349431efa25ee83b7eb4dd5395db63e to your computer and use it in GitHub Desktop.
[get local ip with golang]
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 ( | |
"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