Python使用Whois协议查询域名、IP地址信息
问题由来
查看APNIC的帮助得知它是提供Whois服务的。Whois是老牌因特网协议了,以前听说过,今天研究了一下发现非常简单:协议基于TCP,端口43,客户端连接服务器发送命令和CR、LF,然后服务器返回响应内容并关闭连接。命令和响应都是纯文本格式的,可以直接阅读。这也体现了因特网协议的可读性的设计原则(当然现在的Google之类的没有内涵的公司肯定是不遵循的啦)。
我在Windows下面用Telnet试了一下,貌似有些问题,命令总是发不完整,于是用Python试验,成功了。
Python代码
代码如下,注意接收的时候必须使用循环,哪怕缓冲区再大,也不一定能够一次收完。
import socket
if __name__ == __main__:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((whois.apnic.net, 43))
# 江苏电信DNS地址
s.send(b222.191.251.125
)
result = bytearray()
while True:
data = s.recv(10000)
if not len(data):
break
result.extend(data)
s.close()
print(bytes(result).decode(ascii))
返回可读的信息如下,需要什么解析字符串就是了。
% [whois.apnic.net] % Whois data copyright terms http://www.apnic.net/db/dbcopyright.html % Information related to 222.184.0.0 - 222.191.255.255 % Abuse contact for 222.184.0.0 - 222.191.255.255 is anti-spam@ns.chinanet.cn.net inetnum: 222.184.0.0 - 222.191.255.255 netname: CHINANET-JS descr: CHINANET jiangsu province network descr: China Telecom descr: A12,Xin-Jie-Kou-Wai Street descr: Beijing 100088 country: CN admin-c: CH93-AP tech-c: CJ186-AP mnt-by: APNIC-HM mnt-lower: MAINT-CHINANET-JS mnt-routes: MAINT-CHINANET-JS remarks: This object can only modify by APNIC hostmaster remarks: If you wish to modify this object details please remarks: send email to hostmaster@apnic.net with your remarks: organisation account name in the subject line. status: ALLOCATED PORTABLE last-modified: 2015-08-26T01:26:56Z source: APNIC mnt-irt: IRT-CHINANET-CN irt: IRT-CHINANET-CN address: No.31 ,jingrong street,beijing address: 100032 e-mail: anti-spam@ns.chinanet.cn.net abuse-mailbox: anti-spam@ns.chinanet.cn.net admin-c: CH93-AP tech-c: CH93-AP auth: # Filtered mnt-by: MAINT-CHINANET last-modified: 2010-11-15T00:31:55Z source: APNIC role: CHINANET JIANGSU address: 260 Zhongyang Road,Nanjing 210037 country: CN phone: +86-25-86588231 phone: +86-25-86588745 fax-no: +86-25-86588104 e-mail: ip@jsinfo.net remarks: send anti-spam reports to spam@jsinfo.net remarks: send abuse reports to abuse@jsinfo.net remarks: times in GMT+8 admin-c: CH360-AP tech-c: CS306-AP tech-c: CN142-AP nic-hdl: CJ186-AP remarks: www.jsinfo.net notify: ip@jsinfo.net mnt-by: MAINT-CHINANET-JS last-modified: 2011-12-06T02:58:51Z source: APNIC person: Chinanet Hostmaster nic-hdl: CH93-AP e-mail: anti-spam@ns.chinanet.cn.net address: No.31 ,jingrong street,beijing address: 100032 phone: +86-10-58501724 fax-no: +86-10-58501724 country: CN mnt-by: MAINT-CHINANET last-modified: 2014-02-27T03:37:38Z source: APNIC % This query was served by the APNIC Whois Service version 1.88.15-46 (WHOIS-NODE3)
