python網路作業:使用python的socket庫實現ICMP協議的traceroute
摘要:
直接上程式碼:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 技術支援:https://www.jianshu.com/u/69f40328d4f0
# 技術支援 https://china-testing.github.io/
# h...
直接上程式碼:
#!/usr/bin/python3 # -*- coding: utf-8 -*- # 技術支援:https://www.jianshu.com/u/69f40328d4f0 # 技術支援 https://china-testing.github.io/ # https://github.com/china-testing/python-api-tesing/blob/master/practices/traceroute.py # 討論釘釘免費群21745728 qq群144081101 567351477 # CreateDate: 2018-11-26 import socket import io import struct import sys class flushfile(io.FileIO): def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() sys.stdout = flushfile(sys.stdout) def main(dest_name): dest_addr = socket.gethostbyname(dest_name) port = 55285 max_hops = 30 ttl = 1 while True: rec_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) timeout = struct.pack("ll", 2, 0) rec_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout) rec_socket.bind(("", port)) sys.stdout.write(" %d" % ttl) send_socket.sendto(bytes("", "utf-8"), (dest_name, port)) curr_addr = None curr_name = None finished = False tries = 1 while not finished and tries > 0: try: _, curr_addr = rec_socket.recvfrom(512) finished = True curr_addr = curr_addr[0] try: curr_name = socket.gethostbyaddr(curr_addr)[0] except socket.error: curr_name = curr_addr except socket.error as err: tries -= 1 sys.stdout.write("* ") send_socket.close() rec_socket.close() if not finished: pass if curr_addr is not None: curr_host = "%s (%s)" % (curr_name, curr_addr) else: curr_host = "" sys.stdout.write("%s\n" % (curr_host)) ttl += 1 if curr_addr == dest_addr or ttl > max_hops: break if __name__ == "__main__": main("china-testing.github.io")
參考資料
- ofollow,noindex">本文最新版本地址
- 討論 釘釘群21745728 qq群144081101 567351477
- 本文涉及的python測試開發庫 謝謝點贊!
- 本文相關海量書籍下載
- python 3.7極速入門教程9最佳python中文工具書籍下載
- 最新程式碼地址
執行
注意要有root或管理員許可權:
# python3 traceroute.py china-testing.github.io -t 4 1* 211.223.48.177 (11.223.48.177) 311.223.48.10 (11.223.48.10) 4* 5106.11.37.58 (106.11.37.58) 6116.251.105.229 (116.251.105.229) 7122.224.214.69 (122.224.214.69) 8* 9115.239.209.30 (115.239.209.30) 10* 11* ...