Skip to content

Commit

Permalink
更换获取ip地址源, 新增获取内部 ip, #143
Browse files Browse the repository at this point in the history
  • Loading branch information
iikira committed May 4, 2018
1 parent 34169b4 commit 30f3eb2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
17 changes: 14 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
},
Expand Down
34 changes: 13 additions & 21 deletions pcsutil/getip/getip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 30f3eb2

Please sign in to comment.