计网课设1、课题1:Ping(网络层程序设计,必做) (1)Ping后不加参数实现四次ping。 (2)Ping后增加“-t”参数实现无限次ping。 (3)开发语言为python。
时间: 2024-01-23 09:01:49 浏览: 109
好的,那么以下是一个Python实现的Ping程序的示例代码,可以实现四次Ping和无限次Ping的功能:
```python
import os
import sys
import struct
import time
import select
import socket
def checksum(data):
n = len(data)
m = n % 2
sum = 0
for i in range(0, n-m, 2):
sum += (data[i]) + ((data[i+1])<<8)
if m:
sum += (data[-1])
sum = (sum >> 16) + (sum & 0xffff)
sum += (sum >> 16)
result = ~sum & 0xffff
result = result >> 8 | (result << 8 & 0xff00)
return result
def ping(host, count=4, timeout=2, infinite=False):
icmp = socket.getprotobyname("icmp")
try:
with socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) as sock:
sock.settimeout(timeout)
# create packet
packet_id = os.getpid() & 0xFFFF
packet_seq = 1
header = struct.pack("bbHHh", 8, 0, 0, packet_id, packet_seq)
bytes_in_double = struct.calcsize("d")
data = (192 - bytes_in_double) * "Q"
data = struct.pack("d", time.time()) + bytes(data.encode("utf-8"))
chksum = checksum(header + data)
header = struct.pack("bbHHh", 8, 0, chksum, packet_id, packet_seq)
packet = header + data
while count > 0 or infinite:
# send packet
sent_time = time.time()
sock.sendto(packet, (host, 1))
count -= 1
# receive packet
try:
ready = select.select([sock], [], [], timeout)
if not ready[0]:
print("Request timed out.")
continue
recv_packet, addr = sock.recvfrom(1024)
recv_time = time.time()
delay = round((recv_time - sent_time) * 1000, 2)
print(f"Reply from {addr[0]}: bytes={len(recv_packet)} time={delay}ms")
except socket.timeout:
print("Request timed out.")
continue
packet_seq += 1
header = struct.pack("bbHHh", 8, 0, 0, packet_id, packet_seq)
chksum = checksum(header + data)
header = struct.pack("bbHHh", 8, 0, chksum, packet_id, packet_seq)
packet = header + data
except socket.gaierror as e:
print(f"Address {host} not found: {e}")
except socket.error as e:
print(f"Error: {e}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python ping.py <host> [-t] [-c count] [-w timeout]")
sys.exit(1)
host = sys.argv[1]
infinite = "-t" in sys.argv
count_index = sys.argv.index("-c") if "-c" in sys.argv else -1
count = int(sys.argv[count_index + 1]) if count_index > 0 else 4
timeout_index = sys.argv.index("-w") if "-w" in sys.argv else -1
timeout = int(sys.argv[timeout_index + 1]) if timeout_index > 0 else 2
ping(host, count, timeout, infinite)
```
这个程序使用了Python的socket库进行网络通信,发送和接收ICMP报文进行Ping操作。其中,checksum函数用于计算校验和,ping函数实现了四次Ping和无限次Ping的功能,可以根据参数进行控制。程序支持在命令行中通过参数指定Ping的目标主机、Ping次数、超时时间等参数。
阅读全文