实现原理:
代码实例:
package main
import (
"bytes"
"io"
"net/http"
"time"
)
func main() {
println(IP_Info(`119.29.29.29`))
}
// 获取IP地址
// 参数:IP地址
// 返回:IP地址的信息(格式:字符串的json)
func IP_Info(ip string) string {
client := http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(`http://ip.taobao.com/service/getIpInfo.php?ip=` + ip)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var buffer [512]byte
result := bytes.NewBuffer(nil)
for {
n, err := resp.Body.Read(buffer[0:])
result.Write(buffer[0:n])
if err != nil && err == io.EOF {
break
} else if err != nil {
panic(err)
}
}
return result.String()
}
返回数据:
{
"code": 0,
"data": {
"ip": "119.29.29.29",
"country": "中国",
"area": "",
"region": "北京",
"city": "北京",
"county": "XX",
"isp": "腾讯",
"country_id": "CN",
"area_id": "",
"region_id": "110000",
"city_id": "110100",
"county_id": "xx",
"isp_id": "1000401"
}
}
网友评论