diff --git a/main.go b/main.go index afbf73c8..c6d2ca0e 100644 --- a/main.go +++ b/main.go @@ -1324,10 +1324,21 @@ func main() { }, { Name: "getip", - Usage: "获取IP地址和IP位置", + Usage: "获取IP地址", Action: func(c *cli.Context) error { - ipAddr, location := getip.IPInfo() - fmt.Printf("IP地址: %s, IP位置: %s\n", ipAddr, location) + fmt.Printf("内部IP地址: \n") + for _, address := range pcsutil.ListAddresses() { + fmt.Printf("%s\n", address) + } + fmt.Printf("\n") + + ipAddr, err := getip.IPInfo(pcsconfig.Config.EnableHTTPS()) + if err != nil { + fmt.Printf("获取外部IP错误: %s\n", err) + return nil + } + + fmt.Printf("外部IP地址: %s\n", ipAddr) return nil }, }, diff --git a/pcsutil/getip/getip.go b/pcsutil/getip/getip.go index 43223906..fb49cf41 100644 --- a/pcsutil/getip/getip.go +++ b/pcsutil/getip/getip.go @@ -2,34 +2,26 @@ package getip import ( - "github.com/iikira/BaiduPCS-Go/pcsverbose" "github.com/iikira/BaiduPCS-Go/requester" - "regexp" "unsafe" ) -const ( - //StrUnknown unknown - StrUnknown = "unknown" -) - -var ( - ipExp = regexp.MustCompile("{ip:'(.*?)',address:'(.*?)'}") -) - //IPInfo 获取IP地址和IP位置 -func IPInfo() (ipAddr, location string) { - body, err := requester.Fetch("GET", "http://ip.chinaz.com/getip.aspx", nil, nil) - if err != nil { - pcsverbose.Verbosef("DEBUG: getip: %s\n", err) - return StrUnknown, StrUnknown +func IPInfo(https bool) (ipAddr string, err error) { + c := requester.NewHTTPClient() + c.SetHTTPSecure(https) + + var scheme string + if https { + scheme = "https" + } else { + scheme = "http" } - raw := ipExp.FindSubmatch(body) - if len(raw) < 3 { - pcsverbose.Verboseln("DEBUG: getip: regexp match failed") - return StrUnknown, StrUnknown + body, err := c.Fetch("GET", scheme+"://api.ipify.org", nil, nil) + if err != nil { + return "", err } - return *(*string)(unsafe.Pointer(&raw[1])), *(*string)(unsafe.Pointer(&raw[2])) + return *(*string)(unsafe.Pointer(&body)), nil }