#!/usr/bin/env python#coding:utf-8import os, sys, socket, struct, select, time# from /usr/include/linux/icmp.h; your milage may vary.icmp_echo_request = 8 # seems to be the same on solaris.def checksum(source_string): i'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c sum = 0 countto = (len(source_string)/2)*2 count = 0 while count 16) + (sum & 0xffff) sum = sum + (sum >> 16) answer = ~sum answer = answer & 0xffff # swap bytes. bugger me if i know why. answer = answer >> 8 | (answer << 8 & 0xff00) return answerdef receive_one_ping(my_socket, id, timeout): receive the ping from the socket. timeleft = timeout while true: startedselect = time.time() whatready = select.select([my_socket], [], [], timeleft) howlonginselect = (time.time() - startedselect) if whatready[0] == []: # timeout return timereceived = time.time() recpacket, addr = my_socket.recvfrom(1024) icmpheader = recpacket[20:28] type, code, checksum, packetid, sequence = struct.unpack( bbhhh, icmpheader ) if packetid == id: bytesindouble = struct.calcsize(d) timesent = struct.unpack(d, recpacket[28:28 + bytesindouble])[0] return timereceived - timesent timeleft = timeleft - howlonginselect if timeleft dest_addrcountdest_addrtimeout< and display the result. for i in xrange(count): print ping %s... % dest_addr, try: delay = do_one(dest_addr, timeout) except socket.gaierror, e: print failed. (socket error: '%s') % e[1] break if delay == none: print failed. (timeout within %ssec.) % timeout else: delay = delay * 1000 print get ping in %0.4fms % delayif __name__ == '__main__': verbose_ping(www.163.com,2,1)
希望本文所述对大家的python程序设计有所帮助。
