tcp traceroute
Thomas Guettler
hv at tbz-pariv.de
Wed Nov 28 05:37:01 EST 2007
Hi,
I want to write a small tcp traceroute script. I works, but how
can I get the IP of the hop that send 'no route to host'?
Result:
python tmp/tcptraceroute.py a.b.c.d 80
ttl=01: (113, 'No route to host')
ttl=02: (113, 'No route to host')
ttl=03: (113, 'No route to host')
ttl=04: timed out
ttl=05: timed out
ttl=06: timed out
ttl=07: timed out
ttl=08: timed out
ttl=09: OK
#!/usr/bin/env python
# tcptraceroute.py
# This script is in the public domain
import os
import sys
import struct
import socket
def usage():
print '''Usage: %s host port
Tries to connect to host at TCP port with increasing TTL (Time to live).
''' % os.path.basename(sys.argv[0])
def main():
if not len(sys.argv)==3:
usage()
sys.exit(1)
ttl=1
host, port = sys.argv[1:]
port=int(port)
for ttl in range(1, 30):
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
s.settimeout(2)
try:
s.connect((host, port))
except (socket.error, socket.timeout), err:
print 'ttl=%02d: %s' % (ttl, err)
s.close()
continue
except KeyboardInterrupt:
print 'ttl=%02d (KeyboardInterrupt)' % ttl
break
print 'ttl=%02d: OK' % (ttl)
break
if __name__=='__main__':
main()
More information about the Python-list
mailing list