'My Traceroute script is giving me host name could not be determined error
Here is the CODE:
import socket
import os
import sys
import struct
import time
import select
import binascii
label = '*************{0}*************'
ICMP_ECHO_REQUEST = 8
MAX_HOPS = 30
TIMEOUT = 2.0
TRIES = 1
def checksum(string):
csum = 0
countTo = (len(string) / 2) * 2
count = 0`enter code here`
while count < countTo:
thisVal = (string[count + 1]) * 256 + (string[count])
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
if countTo < len(string):
csum = csum + (string[len(string) - 1])
csum = csum & 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def get_name_or_ip(hostip):
try:
host = socket.gethostbyaddr(hostip)
nameorip = nameorip = '{0} ({1})'.format(hostip, host[0])
return nameorip
except Exception:
nameorip = '{0} (host name could not be determined)'.format(hostip)
return nameorip
def build_packet():
myChecksum = 0
myID = os.getpid() & 0xFFFF
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1)
data = struct.pack("d", time.time())
myChecksum = checksum(header + data)
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, myID, 1)
packet = header + data
return packet
def get_route(hostname):
timeLeft = TIMEOUT
tracelist1 = [] # This is your list to use when iterating through each trace
tracelist2 = [] # This is your list to contain all traces
print(label.format(hostname))
timeLeft = TIMEOUT
for ttl in range(1, MAX_HOPS):
for tries in range(TRIES):
destAddr = socket.gethostbyname(hostname)
icmp = socket.getprotobyname("icmp")
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL,
struct.pack('I', ttl))
mySocket.settimeout(TIMEOUT)
try:
d = build_packet()
mySocket.sendto(d, (hostname, 0))
t = time.time()
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []:
tracelist1.append(str(ttl))
tracelist1.append("* * * Request timed out.")
print(" * * * Request timed out.")
recvPacket, addr = mySocket.recvfrom(1024)
timeReceived = time.time()
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
tracelist1.append(str(ttl))
tracelist1.append("* * * Request timed out.")
print(" * * * Request timed out.")
except socket.timeout:
continue
else:
icmpHeaderContent = recvPacket[20:28]
type, code, checksum, packetID, sequence = struct.unpack("bbHHh", icmpHeaderContent)
printname = get_name_or_ip(addr[0])
if type == 11:
tracelist1.append(str(ttl))
tracelist1.append("* * * Request timed out.")
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print(" %d rtt=%.0f ms %s" % (ttl, (timeReceived - t) * 1000, printname))
elif type == 3:
tracelist1.append(str(ttl))
tracelist1.append("* * * Request timed out.")
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print(" %d rtt=%.0f ms %s" % (ttl, (timeReceived - t) * 1000, printname))
elif type == 0:
tracelist1.append("* * * Request timed out.")
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print(" %d rtt=%.0f ms %s" % (ttl, (timeReceived - timeSent) * 1000, printname))
tracelist1.append(str(ttl))
tracelist2.append(tracelist1)
return tracelist2
else:
print("error")
break
#finally:
mySocket.close()
return tracelist2
if __name__ == '__main__':
get_route("google.co.il")
if len(sys.argv) < 2:
print("End)")
else:
get_route(sys.argv[1])
[1]: https://i.stack.imgur.com/TTSRd.png
Hello Good People,
I have been trying to get this school assignment to work with not avail. Basically we are required to write a traceroute script. Unfortunately, my code returns a lot of "host name could not be determined" messages. I am not sure what to do to resolve it. I am a beginner when it comes to python so please take it easy on me, I am not even sure I completely understand what I am doing from coding perspective. Any help on how to fix this will be greatly appreciated, thank you. [enter image description here][1]
Here are the instructions:
Lab 5: ICMP Traceroute Lab
In this lab you will learn how to implement a traceroute application using ICMP request and reply messages. The checksum and header making are not covered in this lab, refer to the ICMP ping lab for that purpose, the naming of most of the variables and socket is also the same.
Traceroute is a computer networking diagnostic tool which allows a user to trace the route from a host running the traceroute program to any other host in the world. Traceroute is implemented with ICMP messages. It works by sending ICMP echo (ICMP type ‘8’) messages to the same destination with increasing value of the time-to-live (TTL) field. The routers along the traceroute path return ICMP Time Exceeded (ICMP type ‘11’) when the TTL field becomes zero. The final destination sends an ICMP reply
(ICMP type ’0’) messages on receiving the ICMP echo request. The IP addresses of the routers which send replies can be extracted from the received packets. The round-trip time between the sending host and a router is determined by setting a timer at the sending host.
Your task is to develop your own Traceroute application in python using ICMP. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in RFC 1739.
Code
Below you will find the skeleton code for the client. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in start and #Fill in end. Each place may require one or more lines of code.
Additional Notes
1. You do not need to be concerned about the checksum, as it is already given in the assignment skeleton code.
2. This lab requires the use of raw sockets. In some operating systems (e.g. MacOS, Windows), you may need administrator/root privileges to be able to run your Traceroute program.
3. Local testing may require you to turn your firewall or antivirus software off to allow the messages to be sent and received. However, Gradescope is not impacted by this.
4. See the end of Lab 4 ‘ICMP Pinger’ programming exercise for more information on ICMP.
What to Hand in
Use your GitHub repository to upload the complete code for the assignment. The name of the file you submit should be “solution.py”.
Testing the Pinger
Test your client by running your code to trace google.com or bing.com. Your output should return a list and meet the acceptance criteria format provided below.
Output Requirements (Acceptance Criteria)
Your code must produce the traceroute output in the format provided below for Gradescope to verify your code is working correctly.
Your trace must collect hop number, roundtrip time (rtt), host ip, and the hostname. If a hostname is not available for a host, you should provide an explicit hostname as “hostname not returnable”. Also, if a host is timing out (not responding), you must record this in your trace list item with the text “Request timed out”. Example provided below:
Example: 1 12ms 10.10.111.10 hop1.com
2 30ms 10.10.112.10 hostname not returnable
3 * Request timed out
4 5ms 10.10.110.1 target-host.com
Your get_route() function must return a nested list with trace output. That is, each trace row must be a list that includes the trace results as individual items in the list, which is also inside an overall traceroute list. Example provided below:
Example: [ [‘1’, ‘12ms’, ‘10.10.111.10’, ‘hop1.com’], [‘2’, ‘30ms’, ‘10.10.112.10’,
‘hostname not returnable’], [‘3’, ‘*’, ‘Request timed out’], [‘4’, ‘5ms’,
‘10.10.110.1’, ‘target-host.com’] ]
Note: Your output will be parsed to verify that it includes the relevant information, so if you do not provide the output of your function in a nested list, your solution will not work correctly and you will not receive points. Also, note that the example lists include all data as strings.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
