通过套接字socket获得ip_whois的AS字段信息(代码+相关知识补充)
程序员文章站
2022-04-24 22:17:20
...
思路的是通过套接字请求Cymruwhois server(ip为38.229.36.122)的43端口获得相关字段
先分享python的代码
import socket
def get_as(query_ip):
error_as = ''
data = ''
try:
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#创建套接字,AF_INET代表ipv4,SOCK_STREAM代表tcp协议
conn.settimeout(5)
conn.connect(('38.229.36.122', 43))
#conn为socket.socket()返回的套接字对象,连接到Cymruwhois server
# conn.connect(('whois.cryum.com', 43))
# Query the Cymru whois server, and store the results.
conn.send((' -r -a -c -p {0}{1}'.format(query_ip, '\r\n')).encode())
#这里比较复杂,下面再具体说
while True:
da = conn.recv(4096).decode()
#recv是接收远端主机传来的数据,4096是数据大小
data += da
if not da:
break
# parse_as_q.put(data)
except Exception as e:
error_as = str(e)
#如果有错误将其抛出
return (data, error_as)
if __name__ == '__main__':
print(get_as("114.255.225.77"))
conn.send((’ -r -a -c -p {0}{1}’.format(query_ip, ‘\r\n’)).encode())
send函数是向远端主机发送字符串数据
关键是(’ -r -a -c -p {0}{1}’.format(query_ip, ‘\r\n’)怎么理解
format函数我给一个简单的case:
“{1} {0} {1}”.format(“hello”, “world”) 其实就是:
‘world hello world’
现在关键就是前缀 -r -a -c -p 怎么理解了,我在google上查阅到前缀:
begin enable bulk input mode (netcat only)
end exit the whois/netcat client (netcat only)
-p prefix include matching prefix
-q noprefix disable matching prefix (default)
-c countrycode include matching country code
-d nocountrycode disable country codes (default)
-n asname include asnames (default)
-o noasname disable asnames
-r registry display matching registry
-s noregistry disable registry display (default)
-a allocdate enable allocation date
-b noallocdate disable allocation date (default)
-t truncate truncate asnames (default)
-u notruncate do not truncate asnames
-v verbose enable all flags (-c -r -p -a -u -a)
-e header enable column headings (default)
-f noheader disable column headings
-w asnumber include asnumber column (default)
-x noasnumber disable asnumber column (will not work for IP mappings)
-h help this help message
-r代表显示登记处,-p代表显示BGP前缀号,-a代表显示分配的日期,-c代表国家的代码,又asnumber和asname是默认显示的,所以代码运行结果:
('AS | IP | BGP Prefix | CC | Registry | Allocated | AS Name\n
4808 | 114.255.225.77 | 114.255.192.0/18 | CN | apnic | 2008-06-24 | CHINA169-BJ China Unicom Beijing Province Network, CN\n', '')
上一篇: `div`中的内容水平垂直居中
下一篇: web开发的前端