1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| def checksum(self, source_string):
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff
count = count + 2
if countTo<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 recevoir_un_ping(self, mon_socket, ID, timeout):
timeLeft = timeout
while True:
startedSelect = time.clock()
whatReady = select.select([mon_socket], [], [], timeLeft)
howLongInSelect = (time.clock() - startedSelect)
if whatReady[0] == []: return
timeReceived = time.clock()
recPacket, addr = mon_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 <= 0: return
def envoyer_un_ping(self, mon_socket, dest_addr, ID):
dest_addr = socket.gethostbyname(dest_addr)
mon_checksum = 0
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, mon_checksum, ID, 1)
bytesInDouble = struct.calcsize("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d", time.clock()) + data
mon_checksum = self.checksum(header + data)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(mon_checksum), ID, 1)
packet = header + data
mon_socket.sendto(packet, (dest_addr, 1))
def do_one(self, dest_addr, timeout):
icmp = socket.getprotobyname("icmp")
try:
mon_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
return
raise socket.error(msg)
raise
mon_ID = os.getpid() & 0xFFFF
self.envoyer_un_ping(mon_socket, dest_addr, mon_ID)
delay = self.recevoir_un_ping(mon_socket, mon_ID, timeout)
mon_socket.close()
return delay
def verbose_ping(self, dest_addr, timeout = 2, count = 1):
for i in xrange(count):
try:
delay = self.do_one(dest_addr, timeout)
except socket.gaierror, e:
return
break
if delay is None: return False
else: return True
....
def initialize(self):
if self.verbose_ping("monproxy.com"): |