package main import ( "fmt" "net" "regexp" "strings" ) func main() { ips := []string{} addrs, err := net.InterfaceAddrs() if err != nil { panic(err) } for _, addr := range addrs { ip := addr.String() fmt.Println(ip) pos := strings.Index(ip, "/") fmt.Println(pos) if match, _ := regexp.MatchString("(\\d+\\.){3}\\d+", ip); match { if pos != -1 { ips = append(ips, ip[0:pos]) } } } fmt.Println(ips) }
##获取本地主机IP列表
##下面代码是从其他博主复制过来的
package main import ( "fmt" "net" "os" ) func main() { addrs, err := net.InterfaceAddrs() if err != nil { fmt.Println(err) os.Exit(1) } for _, address := range addrs { // 检查ip地址判断是否回环地址 if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { fmt.Println(ipnet.IP.String()) } } } }
##获取外网IP地址
package main import ( "flag" "fmt" "io" "net" "net/http" "os" ) var get_ip = flag.String("get_ip", "", "external|internal") func main() { fmt.Println("Usage of ./getmyip --get_ip=(external|internal)") flag.Parse() if *get_ip == "external" { get_external() } if *get_ip == "internal" { get_internal() } } func get_external() { resp, err := http.Get("http://myexternalip.com/raw") if err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") os.Exit(1) } defer resp.Body.Close() io.Copy(os.Stdout, resp.Body) os.Exit(0) } func get_internal() { addrs, err := net.InterfaceAddrs() if err != nil { os.Stderr.WriteString("Oops:" + err.Error()) os.Exit(1) } for _, a := range addrs { if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { os.Stdout.WriteString(ipnet.IP.String() + "\n") } } } os.Exit(0) }