计算机网络课程设计,要编写一个Ping 程序 或者 tracert 程序 。
不使用C/C++ ,Java 不提供传输层一下的控制。只好使用Python来编写
讲解参考 https://www.cnblogs.com/JetpropelledSnake/p/9177770.html
参考 https://wordpress.youran.me/python-raw-socket-programming/
参考 https://www.cnblogs.com/JenningsMao/p/9487465.html
参考 python struct的用法 https://www.cnblogs.com/sexyboy/p/8509666.html
源码来源 https://github.com/Lingerhk/hacking_script/blob/master/net_attacking/icmp_ping_tool.py
源码是python 2 写的
改一下成python 3
# -*- coding: utf-8 -*- import os import argparse import socket import struct import select import time # 请求回显头 ICMP_ECHO_REQUEST = 8 # Platform specific DEFAULT_TIMEOUT = 2 DEFAULT_COUNT = 1 class Pinger(object): """ Pings to a host -- the Pythonic way""" def __init__(self, target_host, count=DEFAULT_COUNT, timeout=DEFAULT_TIMEOUT): self.target_host = target_host self.count = count self.timeout = timeout # 计算校验和 def do_checksum(self, source_string): """ Verify the packet integritity """ sum = 0 max_count = (len(source_string) / 2) * 2 count = 0 while count < max_count: val = source_string[count + 1] * 256 + source_string[count] sum = sum + val sum = sum & 0xffffffff count = count + 2 if max_count < len(source_string): sum = sum + ord(source_string[len(source_string) - 1]) sum = sum & 0xffffffff sum = (sum >> 16) + (sum & 0xffff) sum = sum + (sum >> 16) answer = ~sum answer = answer & 0xffff answer = answer >> 8 | (answer << 8 & 0xff00) return answer def receive_pong(self, sock, ID, timeout): """ Receive ping from the socket. """ time_remaining = timeout while True: start_time = time.time() readable = select.select([sock], [], [], time_remaining) time_spent = (time.time() - start_time) if readable[0] == []: # Timeout return time_received = time.time() recv_packet, addr = sock.recvfrom(1024) icmp_header = recv_packet[20:28] type, code, checksum, packet_ID, sequence = struct.unpack( "bbHHh", icmp_header ) if packet_ID == ID: bytes_In_double = struct.calcsize("d") time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0] return time_received - t