Exemplo n.º 1
0
    def open_sockets(self):   	
        # Create sockets for the connections.
        self.recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        self.send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)

	    icmp = socket.getprotobyname('icmp')
	    udp = socket.getprotobyname('udp')
Exemplo n.º 2
0
def run(host, port):

    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')

    _ttl = 1
    _hop_max = 30

    while True:
        r_icmp_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        s_udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        s_udp_sock.setsockopt(socket.SOL_IP, socket.IP_TTL, _ttl)
        r_icmp_sock.bind(("0.0.0.0", port))
        s_udp_sock.sendto(b"", (host, port))

        try:
            _addr, _port = r_icmp_sock.recvfrom(1024)[1]
            host_name = socket.gethostbyname(_addr)
            addr_info = socket.getaddrinfo(_addr, _port)
            print("{}. - {}:{}\n{}".format(_ttl, _addr, _port, addr_info))
        except Exception as e:
            print(sys.exc_info()[1])

        s_udp_sock.close()
        r_icmp_sock.close()
        _ttl += 1
        if _ttl >= _hop_max:
            break
Exemplo n.º 3
0
def probe(host, ttl=30):
	sending_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp'))
	receiving_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))

	sending_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
	receiving_socket.bind(('', PORT_NUM))
	receiving_socket.settimeout(3)
	start_probe_time = time.time()
	end_probe_time = time.time()+3 #3 is the timeout
	sending_socket.sendto('', (host, PORT_NUM))
	data = None
	address = None
	name = None

	try:
		data, address = receiving_socket.recvfrom(512)
		address = address[0]
		end_probe_time = time.time()

		try:
			name = socket.gethostbyaddr(address)
			name = name[0]
		except Exception, e:
			name = address
		else:
Exemplo n.º 4
0
def rtt(result):
    port = 33434                                     
    print ("result: ", result)
    rtt = 0.0                                               #  initialize important values
    host_name = result[0]
    host_ip = result[1]
    ttl = result[2]

    udp = socket.getprotobyname("udp")                      #  set up sockets
    icmp = socket.getprotobyname("icmp")             
    timeout = struct.pack("ll", 3, 0)                
    r = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)        #  raw socket: receive ICMP messages
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)       #  raw socket to send UDP packets
    r.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout)    #  timeout
    s.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)                 #  initial TTL for the UDP packet

    send_time = time.time()                 #  record time packet was sent
    s.sendto("", (host_name, port))         #  sends UDP packet to host over port
    current_ip = None                          
    pckt = False                      
    att = 3
    data = ""
    while data != "":                   #  listener
        data, host = r.recvfrom(512)    #  take 512 bytes
    rtt = (time.time() - send_time)     #  in ms
    r.close()                        #  close sockets
    s.close()
    return "{0:.2f}".format(rtt*1000)
Exemplo n.º 5
0
def main(dest_name):
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
    send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
    recv_socket.bind(("", port))
    send_socket.sendto("", (dest_name, port))
    curr_addr = None
    curr_name = None
    try:
        _, curr_addr = recv_socket.recvfrom(512)
        curr_addr = curr_addr[0]
        try:
            curr_name = socket.gethostbyaddr(curr_addr)[0]
        except socket.error:
            curr_name = curr_addr
    except socket.error:
        pass
    finally:
        send_socket.close()
        recv_socket.close()

    if curr_addr is not None:
        curr_host = "%s (%s)" % (curr_name, curr_addr)
    else:
        curr_host = "*"
    print "%d\t%s" % (ttl, curr_host)

    ttl += 1
def distMeasurement(desthost):

    print ("Measure the hop distance and RTT of " + desthost)
    destaddr = socket.gethostbyname(desthost) #get the ip address for a given hsot
    #print (destaddr)
    port = 33435 #port used in the destination port field in udp packet
    udp = socket.getprotobyname("udp")
    icmp = socket.getprotobyname("icmp")
    ttl = 32 #the initial TTL in the ip header will be this
    
    #use UDP segment to test a host, the UDP segment is send to a port that is unlikely to be used in destination host
    #create a sending socket using udp protocol
    sendsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
    sendsocket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) #set the ttl field in IP header
    #create a receiving socket as a raw socket, using icmp protocol, in order to receive all the IP datagram
    recvsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    sendtime = send(destaddr, sendsocket, port) 
    TTL, arrivedtime = getreply(recvsocket, destaddr, port)
    if TTL:
        delay = arrivedtime - sendtime
        delay = 1000*delay #delay is going to be showed in the unit of ms.
        TTL = 32 - TTL #subtracting 32 with the remaining TTL in the header field to get the hop distance
        print ("Destination host: %s, Hop distance: %s, RTT: %1.1fms" %(desthost, TTL, delay))
    sendsocket.close()
    recvsocket.close()
Exemplo n.º 7
0
def trace(address):
    port = 33500
    ttl = 1
    icmp_proto = socket.getprotobyname('icmp')
    upd_proto = socket.getprotobyname('udp')
    while ttl < 127:
        ssocket = socket.socket(type=socket.SOCK_DGRAM, proto=upd_proto)
        rsocket = socket.socket(type=socket.SOCK_RAW, proto=icmp_proto)
        ssocket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        rsocket.bind(('', port))
        ssocket.sendto('', (address, port))

        last_addr = None
        try:
            rsocket.settimeout(20)
            _, last_addr = rsocket.recvfrom(256)
            last_addr = last_addr[0]
            print last_addr
        except socket.timeout:
            print "* * *"
        except socket.error:
            print "* * *"
        finally:
            ssocket.close()
            rsocket.close()

        if last_addr == address:
            break
        else:
            ttl += 1
Exemplo n.º 8
0
    def trace(self):
        """Handles iteration of send/receive messages and setup of sockets.
        Initial ttl=1,  then increments ttl and repeats until the destination
        is reached or *max_hops* is exceeded.
        """
        icmp = socket.getprotobyname('icmp')
        udp = socket.getprotobyname('udp')

        receive_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)

        while True:
            send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
            time_sent = time.time()
            self.send_message(send_socket, self.destination_name)
            current_address, current_name = self.receive_message(receive_socket)
            receive_time = time.time() - time_sent

            if current_address is not None:
                current_host = '{host}  ({address})'.format(host=current_name,
                                                            address=current_address)
            else:
                current_host = '*'
            print("{ttl}\t{host} {time} msec".format(ttl=self.ttl,
                                                     host=current_host,
                                                     time=round(receive_time * 1000, 3)))

            if current_address == self.destination_address or self.ttl >= self.max_hops:
                break
            self.ttl += 1

        send_socket.close()
        receive_socket.close()
Exemplo n.º 9
0
 def __icmpSocket(self):
     '''创建ICMP Socket'''
     if not self.IPv6:
         Sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
     else:
         Sock = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
     return Sock
Exemplo n.º 10
0
def traceroute(dest_addr, max_hops=30, timeout=0.2):
    proto_icmp = socket.getprotobyname('icmp')
    proto_udp = socket.getprotobyname('udp')
    port = 33434

    for ttl in xrange(1, max_hops+1):
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
        rx.settimeout(timeout)
        rx.bind(('', port))
        tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
        tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        tx.sendto('', (dest_addr, port))

        try:
            data, curr_addr = rx.recvfrom(512)
            curr_addr = curr_addr[0]
        except socket.error:
            curr_addr = None
        finally:
            rx.close()
            tx.close()

        yield curr_addr

        if curr_addr == dest_addr:
            break
Exemplo n.º 11
0
	def start(self, *args, **kws):
		with\
				closing(socket.socket( socket.AF_INET,
					socket.SOCK_RAW, socket.getprotobyname('icmp') )) as self.ipv4,\
				closing(socket.socket( socket.AF_INET6,
					socket.SOCK_RAW, socket.getprotobyname('ipv6-icmp') )) as self.ipv6:
			return self._start(*args, **kws)
def raw_traceroute(target, ttl):
    port = 33433
    # icmp = socket.getprotobyname('icmp')
    # udp = socket.getprotobyname('udp')
    recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp'))
    send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
    recv_socket.bind(("", port))
    recv_socket.settimeout(30)
    # Start timing in milliseconds
    t0 = time.time() * 1000.00
    t1 = 0
    send_socket.sendto("", (target, port))

    try:
        #If we receive something, stop the clock
        recv_packet, curr_addr = recv_socket.recvfrom(1024)
        t1 = time.time() * 1000.00
    except socket.error:
        pass
    finally:
        send_socket.close()
        recv_socket.close()

    #If we didn't get an answer, return Nones
    if (t1 == 0):
        return None, None
    else:
        return curr_addr[0], t1 - t0
Exemplo n.º 13
0
def addport( csvline, domain=defaultdomain ):
    """
    Adds a network port to the FMC
    """
    proto,port,name,description = csvline.split(",")

    post_data = { "type": "ProtocolPortObject" }

    try:
        #Checks if proto is a string and a known protocol
        socket.getprotobyname( proto )
    except:
        try:
            #Check if protocol is a number
            int( protocol ) + 1
        except:
            raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( proto ), field="protocol", line=repr( csvline ) ) )
    post_data[ "protocol" ] = proto
    try:
        portname = socket.getservbyname( port )
    except:
        try:
            portname = socket.getservbyport( port )
        except:
            raise ValueError( "addport", "ERROR", "Unknown value: {value} for {field} in csv line: {line}".format( value=repr( port ), field="port", line=repr( csvline ) ) )

    post_data[ "port" ] = port
    post_data[ "overridable" ] = "true"
    post_data[ "description" ] = description
    post_data[ "name" ] = name

    api_path = "/api/fmc_config/v1/domain/" + domain + "/object/protocolportobjects"
    json_resp = requesttofmc( api_path, post_data )
    objectadded( json_resp [ "name" ], json_resp [ "type" ], json_resp [ "id" ] )
    return True
Exemplo n.º 14
0
def main(dest_name, logfilename):
    logfile = open(logfilename, "wb")
    headline = "#time\tduration\tmin\tavg_60\tavg_300\tmax\taddress"
    print headline
    logfile.write(headline + "\n")
    dest_addr = socket.gethostbyname(dest_name)
    port = random.randint(1, 65535)
    icmp = socket.getprotobyname("icmp")
    udp = socket.getprotobyname("udp")
    recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
    # send_socket.setsockopt(socket.SOL_IP)
    recv_socket.bind(("", port))
    curr_addr = None
    curr_name = None
    min_value = 99.0
    max_value = 0.0
    avg_60 = 0.0
    avg_300 = 0.0
    while True:
        starttime = time.time()
        duration = 0
        send_socket.sendto("", (dest_name, port))
        try:
            recv_socket.setblocking(0)
            # set receive timeout in seconds
            ready = select.select([recv_socket], [], [], recv_timeout)
            if ready[0]:
                _, curr_addr = recv_socket.recvfrom(512)
                duration = time.time() - starttime
                curr_addr = curr_addr[0]
                if duration > max_value:
                    max_value = duration
                if duration < min_value:
                    min_value = duration
                avg_60 = (59 * avg_60 + duration) / 60
                avg_300 = (299 * avg_300 + duration) / 300
                output = "%d\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%0.8f\t%s" % (
                    starttime,
                    duration,
                    min_value,
                    avg_60,
                    avg_300,
                    max_value,
                    curr_addr,
                )
                print output
                logfile.write(output + "\n")
                logfile.flush()
            else:
                print "%d Timeout waiting for response" % starttime
        except socket.error:
            pass
        time.sleep(1)
    send_socket.close()
    recv_socket.close()
    logfile.close()
Exemplo n.º 15
0
def PING_START(type, source, alive = 0, timeout = 1.0, ipv6 = 0, number = sys.maxint, node = None, flood = 0, size = ICMP_DATA_STR, status_only = 0):
	repl = ''
	if ipv6:
		if socket.has_ipv6:
			try:
				info, port = socket.getaddrinfo(node, None)
				host = info[4][0]
				if host == node: 
					noPrintIPv6adr = 1
			except:
				repl +=  (u'Не могу найти %s: Неизвестный хост' % node)+'\n'
		else:
			repl +=  u'Недоступно IPv6 для на данной платформе\n'
	else:
		try:
			host = socket.gethostbyname(node)
		except:
			repl +=  (u'Не могу найти %s: Неизвестный хост' % node)+'\n'
	if not ipv6:
		try:
			if int(string.split(host, ".")[-1]) == 0:
				repl +=  u'Нет поддержки пинга в сети'+'\n'
		except:
			repl +=  u'Пинг: ошибка, не корректный запрос'+'\n'
			host = '0.0.0.0'
	if number == 0:
		repl +=  (u'Ошибка количества пакетов на передачу: %s' % str(a))+'\n'
	if alive:
		number = 1
	start, mint, maxt, avg, lost, tsum, tsumsq = 1, 999, 0.0, 0.0, 0, 0.0, 0.0
	if not alive:
		if ipv6 and not status_only:
			if noPrintIPv6adr == 1:
				repl += (u'Пинг: %s : %d байты (40+8+%d)' % (str(node), 40 + 8 + size, size))+'\n'
			else:
				repl += (u'Пинг: %s (%s): %d байты (40+8+%d)' % (str(node), str(host), 40 + 8 + size, size))+'\n'
		elif not status_only:
			repl +=  (u'Пинг: %s (%s): %d байты (20+8+%d)' % (str(node), str(host), 20 + 8 + size, size))+'\n'
	try:
		while start <= number:
			lost += 1
			if ipv6:
				try:
					Psocket = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.getprotobyname("ipv6-icmp"))
				except socket.error, e:
					repl +=  u'Ошибка сокета: %s' % e+u' You must be root (%s uses raw sockets)' % os.path.basename(sys.argv[0])+'\n'
			else:
				try:
					Psocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
				except socket.error, e:
					repl +=  u'Ошибка сокета: %s' % e+u' You must be root (%s uses raw sockets)' % os.path.basename(sys.argv[0])+'\n'
				 
			Packet = Packet_construct(start, size, ipv6)
			try:
				Psocket.sendto(Packet,(node, 1))
			except socket.error, e:
				repl +=  u'Ошибка сокета: %s' % e+'\n'
Exemplo n.º 16
0
def create_sockets(ttl):
    ''"Set up receiving and sending sockets.''"
    recv_socket = socket.socket(
            socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
    send_socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('udp'))
    send_socket.setsockopt(
            socket.SOL_IP, socket.IP_TTL, ttl)
    return recv_socket, send_socket
Exemplo n.º 17
0
 def __init__ (self, domain):
     self.domain = domain
     self.finished = False
     self.ip = DomainLookup.Domain_to_IP(domain)
     self.icmp = socket.getprotobyname('icmp')
     self.udp = socket.getprotobyname('udp')
     self.counter = 0
     self.port = 33434
     self.times = []
Exemplo n.º 18
0
def main(destination):
    # get the IP address of the destination adress
    dest_address = socket.gethostbyname(destination)
    port = 33434
    # gets a particular protocol by name... needed for RAW Sockets
    # it specifies what protocol I want to use
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    # Start the time to live at 1
    ttl = 1
    max_hops = 30

    while True:
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        # bind the adress to recv_socket. empty string because we are accepting
        # packets from any host on port 33434 (unlikely port)
        recv_socket.bind(("", port))

        # Send no data (empty string) to the destination host
        # on an unlikely port
        send_socket.sendto("", (destination, port))

        current_adress = None
        try:
            # get data from the recv_socket,
            # recvfrom() returns the packet data and adress
            # we dont care about the packet data so we use _
            _, current_adress = recv_socket.recvfrom(512)

            # get the IP address
            current_adress = current_adress[0]
            try:
                # reverse DNS lookup
                current_name = socket.gethostbyaddr(current_adress)[0]
            except socket.error:
                current_name = current_adress
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        # print the data
        if current_adress is not None:
                current_host = "%s (%s)" % (current_name, current_adress)
        else:
            current_host = "*"
        print "%d\t%s" % (ttl, current_host)

        ttl += 1
        # break out the loop when the following are true:
        if current_adress == dest_address or ttl > max_hops:
            break
Exemplo n.º 19
0
def main(dest_name):
	port = 33434
	dest_addr = socket.gethostbyname(dest_name)
	icmp = socket.getprotobyname("icmp")
	udp = socket.getprotobyname("udp")
	ttl = 1
	max_hops = 255
	RTT = 0

	print "Destination: %s" % (dest_addr)

	while True:
		# open connections
		recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
		send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
		send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, 255)
		recv_socket.bind(("", port))
		recv_socket.settimeout(10)
		start_time = time.time()
		send_socket.sendto("", (dest_name, port))
		curr_addr = None
		curr_name = None
		try:
			#Throw away the packet into _ and extract IP
			_, curr_addr = recv_socket.recvfrom(1024)
			end_time = time.time()
			curr_addr = curr_addr[0]
			try:
				#Try to get host name by IP
				curr_name = socket.gethostbyaddr(curr_addr)[0]
			except socket.error:
				#If it has no name, just use it's IP
				curr_name = curr_addr
		except socket.timeout:
			print "Socket timed out"
		except socket.error:
			print "Socket error"
		finally:
			send_socket.close()
			recv_socket.close()

		# print data
		if curr_addr is not None:
			RTT = end_time-start_time
			curr_host = "%s (%s) %fs" % (curr_name, curr_addr, RTT)
		else:
			curr_host = "*"
		print "%d\t%s" % (ttl, curr_host)

		ttl += 1

		# break if useful
		if curr_addr == dest_addr or ttl > max_hops:
			print "RTT = %ss" % (RTT)
			print "TTL = %ss" % (ttl)
			break
Exemplo n.º 20
0
def create_sockets(ttl):
  recv_socket = socket.socket(socket.AF_INET,
                              socket.SOCK_RAW,
                              socket.getprotobyname('icmp'))
  send_socket = socket.socket(socket.AF_INET,
                              socket.SOCK_DGRAM,
                              socket.getprotobyname('udp'))
  send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
  recv_socket.setblocking(0)
  return recv_socket, send_socket
Exemplo n.º 21
0
def main(dest_name):
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    max_hops = 30
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    while True:
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        # Build the GNU timeval struct (seconds, microseconds)
        timeout = struct.pack("ll", 5, 0)

        # Set the receive timeout so we behave more like regular traceroute
        recv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout)

        recv_socket.bind(("", port))
        sys.stdout.write(" %d  " % ttl)
        send_socket.sendto("", (dest_name, port))
        curr_addr = None
        curr_name = None
        curr_data = None
        finished = False
        tries = 3
        while not finished and tries > 0:
            try:
                curr_data, curr_addr = recv_socket.recvfrom(512)
                finished = True
                curr_addr = curr_addr[0]
                try:
                    curr_name = socket.gethostbyaddr(curr_addr)[0]
                except socket.error:
                    curr_name = curr_addr
            except socket.error as (errno, errmsg):
                tries = tries - 1
                sys.stdout.write("* ")

        send_socket.close()
        recv_socket.close()

        if not finished:
            pass

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
        else:
            curr_host = ""
        sys.stdout.write("%s\n%s\n" % (curr_data, curr_host))

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break
Exemplo n.º 22
0
def trace(dest, PORTNUM=5005, max_hops=30):
    """Traceroute to specified hostname (e.g. 'google.com'). Can optionally
    specify port to send on (defaults 5005).

    """
    IPADDR = socket.gethostbyname(dest)

    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')

    ack = False
    ttl = 1

    print "Starting trace to {0}, {1}".format(dest, IPADDR)

    while not ack:
        curr_addr, curr_name = None, None

        # Initialize and connect UDP socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        r = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        s.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        r.bind(("", PORTNUM))
        s.sendto("", (IPADDR, PORTNUM))

        try:
            r.settimeout(3)  # don't block forever
            dat, curr_addr = r.recvfrom(512)

            # curr_addr is in form (host, port)
            try:
                curr_name = socket.gethostbyaddr(curr_addr[0])[0]
            except socket.error:
                curr_name = curr_addr[0]

        # Catch timeout errors
        except socket.error:
            pass
        finally:
            s.close()
            r.close()

        if curr_addr is None:
            curr_host = "*"
        else:
            curr_host = "{0} ({1})".format(curr_name, curr_addr[0])
            if curr_addr[0] == IPADDR or ttl > max_hops:
                ack = True

        print "{0}\t{1}".format(ttl, curr_host)

        ttl += 1
Exemplo n.º 23
0
 def _create_socket(self):
     if not utils.is_user_admin():
         # RAW socket need root privilege
         raise OSError("Operation not permitted")
     if self._v6:
         proto = socket.getprotobyname("ipv6-icmp")
     else:
         proto = socket.getprotobyname("icmp")
     # Create RAW socket for ping test
     sock = socket.socket(self._family, socket.SOCK_RAW, proto)
     sock.settimeout(self._timeout)
     return sock
Exemplo n.º 24
0
def gethostIP():
	"""
	This returns the public IP address from where this is being called
	"""
	recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
	send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname("udp"))
	send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, 1)
	recv_socket.bind(("", 33434))
	recv_socket.settimeout(10)
	send_socket.sendto("", ("google.com", 33434))
	_, curr_addr = recv_socket.recvfrom(1024)
	return curr_addr[0]
Exemplo n.º 25
0
def calculateDistance(targetHost, maxHops=16):
    """
    Calculates the number of hops between the source and target hosts

    @type  targetHost: str
    @param targetHost: alphanumeric string representing the host name

    @type  maxHops: int
    @param maxHops: maximum distance (in hops) allowed. Hosts above this limit
    are considered to be unreacheable

    @rtype: int
    @return: 0 for success, -1 for failure
    """
    # convert host names into IP addresses
    destAddress = socket.gethostbyname(targetHost)

    port = 33434
    ttl = 0

    while ttl < maxHops:
        ttl += 1

        # the answers are sent back using ICMP
        icmp = socket.getprotobyname('icmp')
        receiverSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        receiverSocket.setblocking(0)

        # send pings using UDP
        udp = socket.getprotobyname('udp')
        senderSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        senderSocket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        # sender and receiver sockets using traceroute's standard port
        receiverSocket.bind(("", 0))
        senderSocket.sendto("", (targetHost, port))
        receiverAddress = None

        try:
            ready = select.select([receiverSocket],[],[],1.0)
            if ready [0]:
                _, receiverAddress = receiverSocket.recvfrom(512)
                receiverAddress = receiverAddress[0]
        except socket.error:
            pass
        finally:
            senderSocket.close()
            receiverSocket.close()

        # target host reached: return
        elif receiverAddress == destAddress:
            return ttl
Exemplo n.º 26
0
def tracert(dest_name, max_hops=30, timeout=5):
    goal = dest_name
    try:
        dest_addr = socket.gethostbyname(dest_name)
    except socket.gaierror:
        exit("Serious!? Check the address, now!")
    print("Start traceroute to {} ({})".format(dest_name, dest_addr))
    print("#\tIP\t\tCountry\tAS\tHost Name")
    port = 33434
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    while True:
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_socket.settimeout(timeout)
        recv_socket.bind((b"", port))
        send_socket.sendto(b"", (dest_name, port))
        curr_addr = None
        curr_name = None
        try:
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]
            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error as e:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            prefix = int(curr_addr.split('.')[0])
            server = db[prefix]
            whs = whois(curr_addr, server)
            curr_host = "{}\t{}\t{}\t{}".format(curr_addr,
                        whs['country'], whs['AS'], curr_name)
        else:
            curr_host = "*"
        print("{}\t{}".format(ttl, curr_host))

        ttl += 1
        if curr_addr == dest_addr:
            print("{} is reached, for {} hops".format(goal, ttl-1))
            break
        elif ttl > max_hops:
            print("{} is don't reached".format(goal, ttl-1))
            break
Exemplo n.º 27
0
def udptracepath(host, port):
    dest_addr = host
    port = port
    max_hops = 10
    route = []
    icmp = socket.getprotobyname("icmp")
    udp = socket.getprotobyname("udp")
    ttl = 1
    while True:
        if VERBOSE == "1":
            print "ttl:", ttl,
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_socket.bind(("", port))
        send_socket.sendto("", (dest_addr, port))
        curr_addr = None
        curr_name = None
        try:
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
        else:
            curr_host = "*"

        if VERBOSE:
            print "ttl(%d)\t%s" % (ttl, curr_host)
        else:
            print "#",
        print "eof"

        if curr_host != "*":
            route.append(curr_addr)

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break
    return route
Exemplo n.º 28
0
def checkProtocol(protocol):
    try:
        i = int(protocol)
    except ValueError:
        # string
        try:
            socket.getprotobyname(protocol)
        except:
            return False
    else:
        if i < 0 or i > 255:
            return False

    return True
Exemplo n.º 29
0
def main(dest_name):

    # some useful vriables
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    max_hops = 30

    while True:

        # create the sockets
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        # bind the recv socket to listen for all hosts on our port
        # bind the send socket to send to our destination
        recv_socket.bind(("", port))
        send_socket.sendto("", (dest_name, port))

        # try and get data from the address
        curr_addr = None
        try:
            # only want the address not the data
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            # get the name
            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            curr_host = '%s %s' % (curr_name, curr_addr)
        else:
            curr_host = '*'
        
        print '%d\t%s' % (ttl, curr_host)

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break
Exemplo n.º 30
0
def main(dest):
    dest_ip = socket.gethostbyname(dest)
    port = 33434
    icmp = socket.getprotobyname("icmp")
    udp = socket.getprotobyname("udp")

    ttl = 1

    max_hops = 30

    while True:

        recv_socket = socket.socket(socket.AF_INET,socket.SOCK_RAW,icmp)
        send_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,udp)                                    
        send_socket.setsockopt(socket.SOL_IP,socket.IP_TTL,ttl)

        recv_socket.bind(("",port))

        send_socket.sendto("",(dest,port))
        cur_addr =None

        try:
            _,curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close();
            recv_socket.close();

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name,curr_addr)

        else:
            curr_host ="*"

        print"%d\t%s" % (ttl,curr_host)

        

        ttl+=1

        if curr_addr == dest_ip or ttl>max_hops:
            break        
Exemplo n.º 31
0
class ICMP(object):

    ICMP_ECHO_REQ = 0x08
    ICMP_ECHO_REP = 0x00

    PROTO_STRUCT_FMT = "!BBHHH"
    PROTO_CODE = socket.getprotobyname("icmp")

    NBYTES_TIME = struct.calcsize("d")

    def _checksum_wrapper(func):

        if sys.byteorder == "big":

            @wraps(func)
            def _checksum_inner(cls, pkt):
                if len(pkt) % 2 == 1:
                    pkt += "\0"
                s = sum(array.array("H", pkt))
                s = (s >> 16) + (s & 0xffff)
                s += s >> 16
                s = ~s
                return s & 0xffff

        else:

            @wraps(func)
            def _checksum_inner(cls, pkt):
                if len(pkt) % 2 == 1:
                    pkt += "\0"
                s = sum(array.array("H", pkt))
                s = (s >> 16) + (s & 0xffff)
                s += s >> 16
                s = ~s
                return (((s >> 8) & 0xff) | s << 8) & 0xffff

        return _checksum_inner

    @classmethod
    @_checksum_wrapper
    def checksum(cls, pkt):
        pass
def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False):
    """
    Returns either the delay (in ms) or None on timeout.
    """
    delay = None

    try:  # One could use UDP here, but it's obscure
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
    except socket.error as e:
        print("failed. (socket error: '%s')" % e.args[1])
        raise  # raise the original error

    my_ID = os.getpid() & 0xFFFF

    sentTime = send_one_ping(mySocket, destIP, my_ID, mySeqNumber, packet_size)
    if sentTime == None:
        mySocket.close()
        return delay

    myStats.pktsSent += 1

    recvTime, dataSize, iphSrcIP, icmpSeqNumber, iphTTL = receive_one_ping(mySocket, my_ID, timeout)

    mySocket.close()

    if recvTime:
        delay = (recvTime - sentTime) * 1000
        if not quiet:
            print("%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms" % (
                dataSize, socket.inet_ntoa(struct.pack("!I", iphSrcIP)), icmpSeqNumber, iphTTL, delay)
                  )
        myStats.pktsRcvd += 1
        myStats.totTime += delay
        if myStats.minTime > delay:
            myStats.minTime = delay
        if myStats.maxTime < delay:
            myStats.maxTime = delay
    else:
        delay = None
        print("Request timed out.")

    return delay
Exemplo n.º 33
0
def ping(address, payload=None, timeout=2.0, seq_number=0):
    if payload is None:
        payload = b'PING' * 16

    try:
        with socket.socket(socket.AF_INET, socket.SOCK_RAW,
                           socket.getprotobyname('icmp')) as s:
            # Send ICMP_ECHO_REQUEST
            checksum = 0
            header = struct.pack('!BBHHH', ICMP_ECHO_REQUEST, 0, checksum,
                                 os.getpid(), seq_number)
            packet = header + payload
            checksum = icmp_checksum(packet)
            packet = packet[:2] + struct.pack('!H', checksum) + packet[4:]
            send_time = time.perf_counter()
            s.sendto(packet, (address, 0))

            # Receive ICMP_ECHO_REPLY
            current_timeout = timeout
            while True:
                select_time = time.perf_counter()
                readable, _, __ = select.select([s], [], [], current_timeout)
                if len(readable) == 0:
                    current_timeout -= time.perf_counter() - select_time
                    if current_timeout <= 0:
                        return None
                    time.sleep(0)
                else:
                    reply_time = time.perf_counter()
                    packet, address = s.recvfrom(len(payload) + 28)
                    icmp_header = IcmpEchoReplyHeader(
                        *struct.unpack('!BBHHH', packet[20:28]))

                    if icmp_header.type == ICMP_ECHO_REPLY and icmp_header.id == os.getpid() and \
                       icmp_header.seq_number == seq_number:
                        ip_header = IpHeader(
                            *struct.unpack('!BBHHHBBHII', packet[:20]))
                        return IcmpEchoReply(icmp_header, ip_header,
                                             reply_time - send_time,
                                             packet[28:])
    except socket.error as e:
        raise Exception('Ping failed.') from e
Exemplo n.º 34
0
def traceroute(ip_address):
    """ Performs a UDP tracerout to the target IP address.
    This is only performed if the '-tr' option is given. 
    """
    print "<-------------TRACE ROUTE---------------------------->"
    icmp = socket.getprotobyname('icmp')
    max_hops = 30
    ttl = 1
    while True:
        try:
            recv = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
            send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            send.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
            recv.bind(("", 33434))
            send.sendto("", (ip_address, 33434))
        except socket.error, e:
            print "Error:",
            print os.strerror(e.errno)
            return
        address = None
        try:
            _, address = recv.recvfrom(512)
            address = address[0]
            try:
                curr_name = socket.gethostbyaddr(address)[0]
            except socket.error:
                curr_name = address
        except socket.error:
            pass

        send.close()
        recv.close()

        if address is not None:
            curr_host = "%s (%s)" % (curr_name, address)
        else:
            curr_host = "*"
        print "%d\t%s" % (ttl, curr_host)

        ttl = ttl + 1
        if (address == ip_address) or (ttl > max_hops):
            break
Exemplo n.º 35
0
    def connect(self, server: str, port: int) -> None:
        log.debug("WhiskerImmSocket: connect")
        proto = socket.getprotobyname("tcp")
        try:
            self.immsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                         proto)
            self.immsock.connect((server, port))
            self.connected = True
        except socket.error as x:
            self.immsock.close()
            self.immsock = None
            self.error = str(x)
            return

        # Disable the Nagle algorithm:
        self.immsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        log.debug("Immediate port: Nagle algorithm disabled (TCP_NODELAY set)")
        # Set blocking
        self.immsock.setblocking(True)
        log.debug("Immediate port: set to blocking mode")
def doOnePing(destinationAddress, timeout):	
	# 1. Create ICMP socket 
        icmp = socket.getprotobyname("icmp")
        try:
          icmpSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) 
        except socket.error as e:
          if e.errno == 1:
              e.msg = e.msg + ("ICMP messages can only be sent from root user processes")
              raise socket.error(e.msg)
          raise
      
        ID = os.getpid() & 0xFFFF             # get Operating Sys ID
    # 2. Call sendOnePing function    
        sendOnePing(icmpSocket, destinationAddress, ID)
	# 3. Call receiveOnePing function        
        delay = receiveOnePing(icmpSocket, destinationAddress, ID, timeout)
	# 4. Close ICMP socket        
        icmpSocket.close()
	# 5. Return total network delay        
        return delay
def create_raw_socket(dest_address):
    '''
    Creates raw socket using icmp header
    @param: dest_address : destination address
    @return: socket_raw: raw socket

    '''
    
    icmp=socket.getprotobyname("icmp") #gets icmp icmp protocol
    
    try:
        socket_raw = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) #creates raw socket
    except socket.error:
        msg='ICMP failure'
        print ('Socket could not be created. Error Code : ' + msg)
        sys.exit()
    
    
        
    return socket_raw
Exemplo n.º 38
0
def ping_wait(ip_addr, timeout):
    """
    return either delay (in second) or none on timeout.
    """
    # Translate an Internet protocol name to a constant suitable for
    # passing as the (optional) third argument to the socket() function.
    # This is usually only needed for sockets opened in “raw” mode.
    icmp = socket.getprotobyname('icmp')
    try:
        # socket.socket([family[, type[, proto]]])
        # Create a new socket using the given address family(default: AF_INET),
        # socket type(SOCK_STREAM) and protocol number(zero or may be omitted).
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error:
        raise

    #send_ping(my_socket, ip_addr, my_ID)
    delay = receive_ping(my_socket, timeout)
    my_socket.close()
    return delay
Exemplo n.º 39
0
 def single_ping(self, ttl = None):
     icmp = socket.getprotobyname("icmp")
     #Create the ICMP Socket
     icmp_sock= socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
     if(ttl != None): #Riwa & Jaafar
         icmp_sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
     # os.getpid() --> gets process id from the operating system
     PID = os.getpid() & 0xFFFF
     self.send_echo_req(icmp_sock, PID)
     #Send the echo request
     #Stores time that the packet was sent to be used for delay calculations
     try:
         start = time.time()
         pack_delay, recv_packet = self.rec_echo(start,icmp_sock, PID, self.timeout)
         #Receive echo reply and then close the socket as it is no longer needed
         icmp_sock.close()
         return pack_delay, recv_packet #packet delay recieved from the echo reply 
     except Exception:
         icmp_sock.close()
         return (None, None)
Exemplo n.º 40
0
 def __init__(self, host, delay=1.0, its_dead_jim=4,
              verbose=True, persistent=False):
     self.host = host
     self.delay = delay
     self.verbose = verbose
     self.persistent = persistent
     self.obituary_delay = its_dead_jim * delay
     self.pad = "getoff my lawn"         # should be 14 chars or more
     socket.setdefaulttimeout(0.01)
     self.started = 0
     self.thread = None
     self._isup = False
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                               socket.getprotobyname('icmp'))
     try:
         self.sock.connect((host, 22))
     except socket.gaierror as ex:
         self.log("ping socket cannot connect to %s: %s" % (host, ex[1]))
         self.sock.close()
         return
Exemplo n.º 41
0
def main(ip_server, delay):
    """
    
    :param ip_server: 
    :param delay: 
    :return: 
    """
    sequence = 1
    identifier = os.getpid() & 0xFFFF
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                  socket.getprotobyname("icmp"))
    except socket.error, (errno, msg):
        if errno == 1:
            # permit denny
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root.")
            raise socket.error(msg)
        raise
Exemplo n.º 42
0
    def do_one(self, dest_addr, timeout):
        """
        Returns either the delay (in seconds) or none on timeout.
        """
        icmp = socket.getprotobyname("icmp")
        try:
            my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except PermissionError as e:
            e.args = (e.args if e.args else tuple()) + (
                (" - Note that ICMP messages can only be sent from processes"
                 " running as root."), )
            raise

        my_ID = os.getpid() & 0xFFFF

        self.send_one_ping(my_socket, dest_addr, my_ID)
        delay = self.receive_one_ping(my_socket, my_ID, timeout)

        my_socket.close()
        return delay
Exemplo n.º 43
0
 def __init__(self, ip_daddr):
     # We're only interested in ICMP, so happy to have this hard coded.
     try:
         self.icmp_listener = socket.socket(
                 socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")
         )
     except PermissionError as e:
         print(e)
         print("Please run as root!")
         exit(1)
     # TODO: Test Timestamps correctly
     SO_TIMESTAMPNS = 35
     self.icmp_listener.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
     self.ip_daddr = ip_daddr
     self.mutex = threading.Lock()
     logging.debug("Starting")
     self.icmp_packets = dict()
     t = threading.Thread(target=self.listener)
     t.setDaemon(True)
     t.start()
Exemplo n.º 44
0
 def _set_outer_l3v4_fields(self, outer_l3v4):
     """ setup outer l3v4 fields from traffic profile """
     ip_params = {}
     if 'proto' in outer_l3v4:
         ip_params['proto'] = socket.getprotobyname(outer_l3v4['proto'])
         if outer_l3v4['proto'] == 'tcp':
             self.udp_packet = Pkt.TCP()
             self.udp[DST_PORT] = 'TCP.dport'
             self.udp[SRC_PORT] = 'TCP.sport'
             tcp_params = {'flags': '', 'window': 0}
             self._set_proto_fields(UDP, **tcp_params)
     if 'ttl' in outer_l3v4:
         ip_params['ttl'] = outer_l3v4['ttl']
     self._set_proto_fields(IP, **ip_params)
     if 'dscp' in outer_l3v4:
         self._set_proto_addr(DSCP, TYPE_OF_SERVICE, outer_l3v4['dscp'])
     if 'srcip4' in outer_l3v4:
         self._set_proto_addr(IP, SRC, outer_l3v4['srcip4'], outer_l3v4['count'])
     if 'dstip4' in outer_l3v4:
         self._set_proto_addr(IP, DST, outer_l3v4['dstip4'], outer_l3v4['count'])
Exemplo n.º 45
0
    def ping_multi_by_select(self, hosts):
        icmp = socket.getprotobyname("icmp")
        packet = self.get_packet()

        socks = []
        ips = set()
        self.sock_map = {}
        for host in hosts:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
            sock.setblocking(False)
            target_addr = socket.gethostbyname(host)
            self.sock_map[sock] = target_addr
            ips.add(target_addr)
            sock.sendto(packet, (target_addr, 1))
            socks.append(sock)

        active_hosts = self.receive_from_hosts(socks, ips)
        for sock in socks:
            sock.close()
        return active_hosts
Exemplo n.º 46
0
 def do_one_ping(self, dest_addr, timeout):
     """
     Returns either the delay (in seconds) or none on timeout.
     """
     icmp = socket.getprotobyname("icmp")
     try:
         my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
     except socket.error as serr:
         if serr.errno == 1:
             # Operation not permitted
             serr.msg += (
                 " - Note that ICMP messages can only be sent from processes"
                 " running as root.")
             raise socket.error(serr.msg)
         raise  # raise the original error
     my_ID = os.getpid() & 0xFFFF
     self.send_one_ping(my_socket, dest_addr, my_ID)
     delay = self.receive_one_ping(my_socket, my_ID, timeout)
     my_socket.close()
     return delay
Exemplo n.º 47
0
def one_ping(dst_addr, icmp_sq, timeout=2, cmd=b"|cmd=|"):
    try:
        rawsocket = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                  socket.getprotobyname("icmp"))
    except socket.error as e:
        if e.errno == 1:
            msg = "{0} please run as root ".format(e)
            raise socket.error(msg)
        raise

    icmp_id = os.getpid() & 0xFFFF

    send_time, addr = send_one_ping(rawsocket,
                                    dst_addr,
                                    icmp_id,
                                    icmp_sq,
                                    cmd=cmd)
    time, type, code, checksum, packet_id, sequence, all_icmpHeader = recv_one_ping(
        rawsocket, icmp_id, icmp_sq, send_time, timeout)
    return time, type, code, checksum, packet_id, sequence, addr, all_icmpHeader
 def ping_once(self):
     """
   Returns the delay in seconds, or none on timeout
   """
     icmp = socket.getprotobyname("icmp")
     msg = ''
     try:
         sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
     except socket.error as errno:
         if errno == 1:
             # Not SuperUser or Root, so the operation is not permitted
             msg += "ICMP messages can only be sent from processes with root user permission"
             raise socket.error(msg)
     except Exception as e:
         print("Exception: (%s)" % e)
     my_ID = os.getpid() & 0xFFFF
     self.send_ping(sock, my_ID)
     delay = self.receive_pong(sock, my_ID, self.timeout)
     sock.close()
     return delay
Exemplo n.º 49
0
def ping(addr):
    print "PING (%s): %d data bytes" % (addr, datalen)

    ## create socket
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                      socket.getprotobyname('icmp'))
    s.connect((addr, 22))

    ## setuid back to normal user
    os.setuid(os.getuid())

    seq_num = 0
    packet_count = 0
    process_id = os.getpid()
    base_packet = Packet((8, 0))

    while 1:
        ## create ping packet
        seq_num += 1
        pdata = struct.pack("!HHd", process_id, seq_num, time.time())

        ## send initial packet
        base_packet.data = pdata
        s.send(base_packet.packet)

        ## recv packet
        buf = s.recv(BUFSIZE)
        current_time = time.time()

        ## parse packet; remove IP header first
        r = Packet.parse(buf[20:])

        ## parse ping data
        (ident, seq, timestamp) = struct.unpack("!HHd", r.data)

        ## calculate rounttrip time
        rtt = current_time - timestamp
        rtt *= 1000
        print "%d bytes from %s: id=%s, seq=%u, rtt=%.3f ms" % (
            len(buf), addr, ident, seq, rtt)
        time.sleep(1)
Exemplo n.º 50
0
def wyslij(id_komunikatu, dane):
    try:
        #print("wyslij")
        proto = socket.getprotobyname('tcp')
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto)

        sock.connect(("192.168.1.201", 1001))
        # msg = bytearray.fromhex(toHex(id_komunikatu))
        #print("id hex = ", toHex(id_komunikatu))

        msg = bytearray()
        msg.append(0xAA)
        # b4 = (id_komunikatu >> 24) & 0xFF;
        # print("4 hex = ", toHex(b4))
        # msg.append(b4)
        # msg.append(0x30)
        # b3 = (id_komunikatu >> 16) & 0xFF;
        # print("3 hex = ", toHex(b3))
        # msg.append(b3)
        # msg.append(0x10)
        b2 = (id_komunikatu >> 8) & 0xFF;
        # print("2 hex = ", toHex(b2))
        msg.append(b2)
        # msg.append(0x02)
        b1 = (id_komunikatu) & 0xFF;
        # print("1 hex = ", toHex(b1))
        msg.append(b1)
        # msg.append(0x01)

        for val in dane:
            msg.append(val)
        msg.append(hap_crc(msg))
        msg.append(0xA5)

        sock.sendall(msg)
        print('wyslano =', binascii.hexlify(msg))
        # sock.sendall(bytearray(b'\xaa\x10\x90\xf0\xf0\xff\xff\x02\x01\xff\xff\xff\xff}\xa5'))
    except socket.error:
        pass
    finally:
        sock.close()
Exemplo n.º 51
0
Arquivo: ping.py Projeto: SPQsmk/PING
def do_one(dest_addr, timeout):
    icmp = socket.getprotobyname("ICMP")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error as err:
        errno, msg = err.errno, err.strerror
        if errno == 1:
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root.")
            raise socket.error(msg)
        raise

    # берем последние два байта
    my_id = os.getpid() & 0xFFFF

    send_one_ping(my_socket, dest_addr, my_id)
    delay = receive_one_ping(my_socket, my_id, timeout)

    my_socket.close()
    return delay
Exemplo n.º 52
0
def do_one(dest_addr, timeout, psize):
    """
    Returns either the delay (in seconds) or none on timeout.
    """
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error as xxx_todo_changeme:
        (errno, msg) = xxx_todo_changeme.args
        if errno == 1:
            # Operation not permitted
            msg = msg + (
                " - Note that ICMP messages can only be sent from processes"
                " running as root.")
            raise socket.error(msg)
        raise  # raise the original error
    my_id = os.getpid() & 0xFFFF
    send_one_ping(my_socket, dest_addr, my_id, psize)
    delay = receive_one_ping(my_socket, my_id, timeout)
    my_socket.close()
    return delay
Exemplo n.º 53
0
    def ping_once(self):
        """
        Returns the delay (in seconds) or none on timeout.
        """
        icmp = socket.getprotobyname("icmp")
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        except socket.error as e:
            if e.errno == 1:
                # Not superuser, so operation not permitted
                e.msg += "ICMP messages can only be sent from root user processes"
                raise socket.error(e.msg)
        except Exception as e:
            print("Exception: %s" % (e))

        my_ID = os.getpid() & 0xFFFF

        self.send_ping(sock, my_ID)
        delay = self.receive_pong(sock, my_ID, self.timeout)
        sock.close()
        return delay
Exemplo n.º 54
0
    def load_from_config(cls, config):
        params = {
            'name': config['name'],
            'host': config.get('host', 'localhost'),
            'port': int(config.get('port', '8080')),
            'path': config.get('path'),
            'interface': config.get('interface', None),
            'family': _FAMILY[config.get('family', 'AF_INET').upper()],
            'type': _TYPE[config.get('type', 'SOCK_STREAM').upper()],
            'backlog': int(config.get('backlog', 2048)),
            'umask': int(config.get('umask', 8))
        }
        proto_name = config.get('proto')
        if proto_name is not None:
            params['proto'] = socket.getprotobyname(proto_name)
        s = cls(**params)

        # store the config for later checking if config has changed
        s._cfg = config.copy()

        return s
Exemplo n.º 55
0
    def _create_socket(self):
        try:
            socket.inet_pton(socket.AF_INET, self.dest)
            dest_ip = self.dest
        except socket.error:
            try:
                dest_ip = socket.gethostbyname(self.dest)
            except socket.gaierror:
                self.ret_code = EXIT_STATUS.ERROR_HOST_NOT_FOUND
                return
        self.dest_ip = dest_ip

        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                      socket.getprotobyname("icmp"))
        except socket.error as e:
            if e.errno == 1:
                self.ret_code = EXIT_STATUS.ERROR_ROOT_REQUIRED
            else:
                self.ret_code = EXIT_STATUS.ERROR_CANT_OPEN_SOCKET
            return
Exemplo n.º 56
0
def do_one(destination, timeout, sequence_num):
    """ Completes an entire ping packet send/receive and returns the time taken for this process
    :param destination: the host to ping
    :param timeout: the maximum time to wait for a response to the ping
    :param sequence_num: the sequence number of the ping
    :return: the time taken to complete the ping or None on timeout
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                             socket.getprotobyname("icmp"))
    except socket.error:
        print("oops")
        sys.exit()

    process_id = os.getpid() & 0xFFFF

    send_one_ping(sock, destination, process_id, sequence_num)
    delay = receive_one_ping(sock, timeout)

    sock.close()
    return delay
Exemplo n.º 57
0
def do_one(dest_addr, timeout):
    """
  Returns either the delay (in seconds) or none on timeout.
  """
    delay = None
    icmp = socket.getprotobyname("icmp")
    try:
        my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        my_ID = os.getpid() & 0xFFFF
        send_one_ping(my_socket, dest_addr, my_ID)
        delay = receive_one_ping(my_socket, my_ID, timeout)
        my_socket.close()
    except socket.error:
        if errno == 1:
            # Operation not permitted
            msg = msg + (" - not root.")
            raise socket.error(msg)
        #raise # raise the original error
    except Exception as e:
        print(e)
    return delay
Exemplo n.º 58
0
    def __init__(self, destination, protocol, source=None, options=()):
        """Creates a network socket to exchange messages

        :param destination: Destination IP address
        :type destination: str
        :param protocol: Name of the protocol to use
        :type protocol: str
        :param options: Options to set on the socket
        :type options: tuple
        :param source: Source IP to use - implemented in future releases
        :type source: Union[None, str]"""
        self.destination = socket.gethostbyname(destination)
        self.protocol = socket.getprotobyname(protocol)
        if source is not None:
            raise NotImplementedError(
                'PythonPing currently does not support specification of source IP'
            )
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                    self.protocol)
        if options:
            self.socket.setsockopt(*options)
Exemplo n.º 59
0
def ParseProtocol(protocol_string):
    """Attempt to parse a protocol number from a string.

  Args:
    protocol_string: The string to parse.

  Returns:
    The corresponding protocol number.

  Raises:
    ValueError: If the protocol_string is not a valid protocol string.
  """
    try:
        protocol = socket.getprotobyname(protocol_string)
    except (socket.error, TypeError):
        try:
            protocol = int(protocol_string)
        except (ValueError, TypeError):
            raise ValueError('Invalid protocol: %s' % protocol_string)

    return protocol
Exemplo n.º 60
0
def send_command(msg, host):
    protocol = 'udp'
    service = 'predict'
    try:
        port = socket.getservbyname(service, protocol)
    except IOError as ex:
        try:
            port = int(service)
        except ValueError:
            raise ex
    addr = socket.gethostbyname(host)
    proto = socket.getprotobyname(protocol)
    if protocol == 'udp':
        type_ = socket.SOCK_DGRAM
    else:
        type_ = socket.SOCK_STREAM
    with socket.socket(socket.AF_INET, type_, proto) as sock:
        sock.settimeout(1)
        sock.sendto(bytes(msg + '\n', 'utf-8'), (host, port))
        resp, server = sock.recvfrom(1024)
    return resp.decode('utf-8')