我找到了一个实现Traceroute的python项目,但它不起作用。 这是项目:
import socket
import sys
class TraceRoute(object):
BADDR = "0.0.0.0" # default bind address - (all IPs)
PORT = 33434 # default port
ICMP = socket.getprotobyname('icmp')
UDP = socket.getprotobyname('udp')
destination = ""
ttl = 0 # increase ttl by one each time.
# sockets
reciever = None
sender = None
# finished?
finished = False
def __init__(self, addr):
self.destination = socket.gethostbyname(addr)
self.reciever = socket.socket(socket.AF_INET, socket.SOCK_RAW, self.ICMP)
self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, self.UDP)
# bind to reciever so we can listen for replies
self.reciever.bind(('', self.PORT))
def next_server(self):
""" Connects to next server 1 hop away from current server (i.e. server[ttl + 1]) """
if self.finished:
# we have nothing to do, just return
return
# first job increment the ttl on the socket
self.ttl += 1
self.sender.setsockopt(socket.SOL_IP, socket.IP_TTL, self.ttl)
self.sender.sendto("", (self.destination, self.PORT))
current_server = self.reciever.recvfrom(512)[1][0] # get 512 bytes from the reciever
print current_server
self.display(current_server)
if current_server == self.destination:
self.finished = True
def display(self, address):
""" Gets the hostname (if we can) and displays """
try:
name = socket.gethostbyaddr(address)[0]
print "%s) %s (%s)" % (self.ttl, name, address)
except socket.error:
# we couldn't - we'll just tell them the IP address
print "%s) %s" % (self.ttl, address)
def __del__(self):
""" close our sockets """
try:
self.reciever.close()
except socket.error:
# already closed
pass
try:
self.sender.close()
except socket.error:
# already closed
pass
if __name__ == "__main__":
# lets get the address from the commandline args
if len(sys.argv) <= 1:
# nothing been specified
print "You need to give an address"
print "%s <server>" % sys.argv[0]
sys.exit() # we can't do anything.
tracert = TraceRoute(sys.argv[1])
while not tracert.finished:
tracert.next_server()
我运行该项目并且卡在这一行:
current_server = self.reciever.recvfrom(512)[1][0]
在查看Wireshark后,我发现我收到了ICMP响应但我的python项目由于某种原因没有捕获并收到它,因此它无法继续并通过该行。
帮助?
答案 0 :(得分:0)
我目前正在Windows上编写一个traceroute项目, 而且我遇到了与您完全相同的问题, socket.recvfrom在我的计算机上什么都没收到, 但是,它可以在其他计算机上正常工作。
我发现实际上是Windows Defender始终阻止答复消息。 关闭Windows Defender之后,我开始收到所有这些被阻止的消息。 希望这对您有所帮助(尽管可能为时已晚)。