# ping.py # python raw socket sample, (c) awarenetwork.org # only works with the raw socket patch and only # on windows 2003 server edition or other windows # Versions that support raw sockets. from rawsock import * from time import time as GetTickCount, sleep as Sleep # returns ( time, IPID ) where time is the time in seconds # it took for the echo reply to arrive and IPID is the # IP ID used in the remote end's packet. def ping(destination, timeout=2.0, length=10, ppp=True): ip = ipv4() icmp1 = icmp() icmp2 = icmp() r = rawsocket() if ppp: r.create(r.ppp0()) else: r.create(r.eth0()) ip.SourceIP = r.getsockname()[0] ip.DestinationIP = destination ip.Protocol = IPPROTO_ICMP icmp1.MakeEcho(Random(0xFFFF),Random(0xFFFF)) icmp1.Payload = length*"." ip.Payload = icmp1 t = GetTickCount() r.sendto(str(ip),(gethostbyname(destination),0)) r.setblocking(0) while (GetTickCount()-t) < timeout: try: _p = r.recvfrom(4000) except: Sleep(0.01); continue ip.read(_p[0]) if (inet_addr(ip.SourceIP) == inet_addr(destination)) and (ip.Protocol == IPPROTO_ICMP): icmp2.read(ip.Payload) if (icmp1.GetDWORD() == icmp2.GetDWORD()) and (icmp1.Payload == icmp2.Payload): return (GetTickCount()-t,ip.Identification) return None