package main import ( "errors" "flag" "fmt" "io/ioutil" "log" "net" "net/http" "os" "strings" "time" ) var ( port string host string showVer bool ) var name string var Version = "v0.1.0" var Build = "v0.1.0" func init() { name, _ = os.Hostname() flag.BoolVar(&showVer, "v", false, "show version") flag.StringVar(&host, "u", "kumoly.io", "hostname to ask for") flag.StringVar(&port, "p", "5080", "port to listen|connect") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: myip-basic [options]\n") flag.PrintDefaults() } } func main() { flag.Parse() if showVer { fmt.Println(Version + "-" + Build) return } fmt.Printf("%s ", GetPublicIP()) for _, v := range GetLocalIP() { fmt.Printf("%s ", v) } fmt.Printf("\n") } func GetLocalIP() []string { ret := []string{} ifaces, err := net.Interfaces() if err != nil { log.Println(err) return ret } for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { log.Println(err) return ret } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP if ip.IsLoopback() { continue } if ip.To4() == nil { continue } default: continue } ret = append(ret, ip.String()) break } } return ret } func GetPublicIP() string { protocol := "http://" req, _ := http.NewRequest("GET", protocol+host+":"+port+"?name="+name, nil) client := &http.Client{ Timeout: time.Second * 10, } res, err := client.Do(req) if err != nil { log.Println(err) return "" } if res.StatusCode != 200 { err = errors.New("http status error: " + res.Status) log.Println(err) return "" } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { log.Println(err) return "" } return strings.TrimRight(string(body), "\r\n") }