Hack Forums
[Python] Traceroute program - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Traceroute program (/showthread.php?tid=4786008)



Traceroute program - Dr_Ciphers - Apr 19, 2015

I have the following python code which implements a traceroute program. The python that i'm using is the 2.7.8

Code
#!/usr/bin/python

import sys
import socket

def main():
      if len(sys.argv) > 1:
      dest_name = sys.argv[1]
      else:
      print("traceroute.py hostname")
      sys.exit(0)

      #define destination address from hostname
      dest_addr = socket.gethostbyname(dest_name)

      #Return the protocol number for the icmp protocol.
      icmp = socket.getprotobyname('icmp')

      #Return the protocol number for the udp protocol.
      udp = socket.getprotobyname('udp')      

      #define ttl as 1 since we want to increment it gradually
      ttl = 1

      port = 33434

      while True:
      #we need two sockets for our connection. One for sending packets and one for receiving
      #we are going to receive the routers and servers responses in icmp.
      #we are going to send packets by using the udp

      #create socket for the icmp packets
      recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)

      #create a socket for the udp packets
      send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)  

      #create a send socket object for sending udp packets
      a= send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

      recv_socket.bind(("", port))
      send_socket.sendto("", (dest_name, port))

      ttl +=1

      # ... open connections ...
      # ... print data ...
      # ... break if useful ...      
      pass

if __name__ == '__main__':
      main()

Although when executed i get the following error.

Traceback (most recent call last):
File "./traceroute.py", line 56, in <module>
main()
File "./traceroute.py", line 39, in main
a= send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument

Any ideas would be appreciated!
Thank you.


* - MR.FREE - Apr 19, 2015

Errno 22 is because your trying to connect to a none existent server/port
http://pastebin.com/BEgFdbfS
Spoiler (Click to View)
Below works for me.
Spoiler (Click to View)


* - Dr_Ciphers - Apr 21, 2015

Thank you MR. FREE. I'm doing modifications on my code and will check it again.