获取公网IP的方法其实很简单,最简单的就是利用dnspod的服务,echo `nc ns1.dnspod.net 6666`,立刻就出来了。于是hugozhu的一段代码就是这样写的:
XML/HTML代码
- func GetLocalPublicIpUseDnspod() (string, error) {
- timeout := time.Nanosecond * 30
- conn, err := net.DialTimeout("tcp", "ns1.dnspod.net:6666", timeout*time.Second)
- defer func() {
- if x := recover(); x != nil {
- log.Println("Can't get public ip", x)
- }
- if conn != nil {
- conn.Close()
- }
- }()
- if err == nil {
- var bytes []byte
- deadline := time.Now().Add(timeout * time.Second)
- err = conn.SetDeadline(deadline)
- if err != nil {
- return "", err
- }
- bytes, err = ioutil.ReadAll(conn)
- if err == nil {
- return string(bytes), nil
- }
- }
- return "", err
- }
上面的原始代码在:http://hugozhu.myalert.info/2013/02/26/dynamic-dns-script.html,原文的代码中其实是不能运行的。因为:timeout是个未定义的变量。
OK,不说这个。我在现实中不能使用上面的代码,因为nc ns1.dnspod.net取出来的结果不正确。为什么?因为我用的是铁通,好象会经过一层代理。但是我访问ip138又是可以取到真实的公网IP,所以我使用了如下代码 :
XML/HTML代码
- func GetLocalPublicIp() (string, error) {
- // `nc ns1.dnspod.cn 6666`
- res, err := http.Get("http://iframe.ip138.com/ic.asp")
- if err != nil {
- return "", err
- }
- defer res.Body.Close()
- result, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return "", err
- }
- reg := regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)
- return reg.FindString(string(result)), nil
- }
上面我用的正则十分简单。就这样写写算了。因为这个页面里就这么一个符合的地方。OK,现在就一切正常了
一直以为wget只是下载点东西的工具。看到一篇网上的文章,才注意到wget原来还可以post数据。
为什么我想用wget来post数据呢?是因为。。。busybox不带curl,而bash版的ddns更新(dnspod的域名更新)是使用curl的。既然curl不支持,我就google了一下:wget能够post数据吗?
果然,第一篇就是:
http://hi.baidu.com/hhflying/item/7ae51f3d30ce64fdde2221d9
- 这段时间需要用wget做一些事情,主要是抓取网页的数据工作,发现wget还是很强大的。下面是一些应用场景:
- 1. 简单页面的抓取
- wget的最基本用法
- wget http://domain.com/path/simple_page.html
- 2. 添加自己的head
- 有些网站或者页面,需要额外的认证,所以需要添加额外的HTTP Header,使用方法:
- wget --header="MyHeader: head_value" http://domain.com/path/page/need_header.php
- 3. 伪装成浏览器
- 有些网站,例如facebook,会检测请求方式是否是浏览器,如果不是正常的浏览器,那么会redirect到一个"incompatible browser"的错误页面。这时候需要wget伪装成一个浏览器(我是Mozilla Firefox!):
- wget --user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (.NET CLR 3.5.30729)" http://domain.com/path/page/check_user_agent.php
- 4. post数据到某个页面
- wget不光可以用get方式请求网页,还可以post data的,那样就可以实现自动注册、自动登录了(有验证码的页面除外。。。。)
- wget --post-data="user=user1&pass=pass1&submit=Login" http://domain.com/login.php
- 5. 访问需要登录的页面
- 有些页面的访问需要登录,访问的时候需要传递cookie,这时候就需要和上面提到的post方式结合。一般过程是:post用户名和密码登录、保存cookie,然后访问页面时附带上cookie。
- wget --post-data="user=user1&pass=pass1&submit=Login" --save-cookies=cookie.txt --keep-session-cookies http://domain.com/login.php
- wget --load-cookies=cookie.txt http://domain.com/path/page_need_login.php
- 暂时就探索到这些,以后有什么新的用法,继续补充。
不过,可惜的是,我运行下来之后,还有一个小问题:
https://dnsapi.cn/Record.Ddns: HTTPS support not compiled in.
哎。。。我没有openssl,https不支持啊。。纠结,uis2000的路真难走。