现在大多说人都是利用www.ip138.com 来查询ip所在的地理位置。
我们利用网页来查询就是提交了一个表单。向服务器传递了两个变量ip和action。
<form method="post" action="ips.asp" target="_blank" name="ipform" onsubmit="return checkIP();"></form> <tr> <td align="center"><div align="center"> <p>在下面输入框中输入您要查询的IP地址或者域名,点击查询按钮即可查询该IP所属的区域。</p> <p>IP地址或者域名:<input name="ip" size="16" type="text"> <input value="查询" type="submit"><input name="action" value="2" type="hidden"></p></div></td> </tr> |
其中action是隐藏的,ip就是我们要查询的ip地址或者域名。onsubmit=”return checkIP();是检查我们的ip输入格式是否正确。
首先我们用curl来向服务器做查询请求:
curl -s -d “ip=XXX&action=2” http://www.ip138.com/ips.asp
其中-d 一个POST请求,ip=后面跟着的是ip地址或者域名,action=2是固定的。
这样服务器会向我们返回一个编码为gb2312的网页,其中包含我们查询的结果。
然后通过管道传到iconv -f gb2312 -t utf-8 转换为utf-8。
得到的网页有这个么几行:
<tr> <td align="center"> <h3>ip138.com IP查询(搜索IP地址的地理位置)</h3> </td> </tr> <tr> <td align="center"><h1><font color="blue">www.baidu.com >> 202.108.22.5</font></h1></td> </tr> <tr> <td align="center"><ul class="ul1"><li>本站主数据:北京市 网通</li><li>参考数据一:北京市 网通</li><li>参考数据二:北京市 百度蜘蛛</li></ul></td> </tr> |
最后一行就是我们要的数据,我们通过grep找到这一行。有css的样式id为ul1 ,所以为grep ‘ul class=”ul1″‘。最终我们得到:
<td align="center"><ul class="ul1"><li>本站主数据:北京市 网通</li><li>参考数据一:北京市 网通</li><li>参考数据二:北京市 百度蜘蛛</li></ul></td> |
最后通过sed把html的标记去除和转换。
sed -e 's/^.*"><li>/\t/' -e 's/<\/li><li>/\n\t/g' -e 's/<.*$//' |
-e 's/^.*"><li>/\t/' |
这个的意思是把这一行开始到最后变为\t 。就是本站主数据前面的东东都为\t.
然后把
</li></li>
变为
\n\t. |
最后是参考数据二后面的<到最后全部删除。
curl -s -d "ip=$1&action=2" http://www.ip138.com/ips.asp|iconv -f gb2312 -t utf-8|grep 'ul class="ul1"'|sed -e 's/^.*"><li>/\t /' -e 's/<\/li><li>/\n\t/g' -e 's/<.*$//' |
$1 为要查询的的ip或者域名。
这里没有考虑到ip不正确或者域名解析不成功的情况。
IP地址:
The best information i have found exactly here. Keep going Thank you