Created
December 16, 2016 06:59
-
-
Save xigang/bd435bd1b5578453e0ccc85229630441 to your computer and use it in GitHub Desktop.
获取本地ip地址
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" | |
| "sort" | |
| "strings" | |
| ) | |
| func main() { | |
| fmt.Println(GetLocalAddrs()) | |
| } | |
| //获取本地ip地址 | |
| func GetLocalAddrs() []string { | |
| addr_list := []string{} | |
| addrs, err := net.InterfaceAddrs() | |
| if err != nil { | |
| panic(err) | |
| } | |
| for _, addr := range addrs { | |
| s := addr.String() | |
| if !strings.ContainsAny(s, ":") && strings.ContainsAny(s, "/") && !strings.Contains(s, "127.0.0.1") { | |
| a := strings.Split(s, "/") | |
| if len(a) == 2 && a[0] != "172.17.42.1" { | |
| addr_list = append(addr_list, a[0]) | |
| } | |
| } | |
| } | |
| sort.Strings(addr_list) | |
| return addr_list | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment