gpt4 book ai didi

python - 为什么我的跟踪路由在运行过程中无法联系服务器?

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:04 25 4
gpt4 key购买 nike

我一直在努力让我的跟踪路由启动并运行,我希望得到一些帮助。我在 Linux VM 上使用 Python 2.7 运行它。下面是我的源代码(请忽略第一行的空格;我很难弄清楚 SO 的代码格式化工具,但我的本地副本中的缩进是正确的。)

def main(dest_name):

dest_addr = socket.gethostbyname(dest_name)
# Define UDP and ICMP
udp = socket.getprotobyname('udp')
icmp = socket.getprotobyname('icmp')
timer = 1
port = 54321
maxHops = 40
totalRTT = 0

while True:
# Create sender and receiver. Sender uses UDP, receiver uses IDMP
sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)

# Assign TTL to sender, increment TTL
sender.setsockopt(socket.SOL_IP, socket.IP_TTL, timer)

receiver = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
receiver.settimeout(15.0)

# Bind socket and send message from sender to receiver
receiver.bind(("", port))
sender.sendto("", (dest_name, port))

# Ensures that not receiving won't stall the program
# receiver.setblocking(0)

addr = None
name = None
count = 0

try:
# Keep track of RTT
startTime = time.time()
# Reads an array of 512-byte sized blocks from sender into addr
(_,addr) = receiver.recvfrom(512)
addr = addr[0]
# Try to get site name
try:
name = socket.gethostbyaddr(addr)[0]
except socket.error:
name = addr
# Process socket errors
except socket.error as exc:
pass
# Close both sockets
finally:
sender.close()
receiver.close()
endTime = time.time()
# Record RTT, total RTT, convert to ms
RTT = (endTime - startTime) * 1000
totalRTT += RTT

if addr is not None:
host = "%s (%s)" % (name, addr)
else:
host = "*"
print("%d\t%s" % (timer, host))
print(" %f" % RTT + " ms")

timer += 1
if addr == dest_addr or timer > maxHops:
print("Total RTT: %f\n" % totalRTT)
print("Hop count: %d\n" % timer)
break

if __name__ == "__main__":
main('www.google.com')

我的输出看起来像这样:

1       129.22.144.2 (129.22.144.2)
3.091097 ms
2 10.2.0.98 (10.2.0.98)
4.683971 ms
3 10.2.3.169 (10.2.3.169)
6.258011 ms
4 *
15015.315056 ms
5 *
15015.240908 ms

它会继续超时,直到达到我的最大跳数。有人有建议吗?

谢谢!

最佳答案

做了一些研究。问题最终出在我使用的端口号上。编写traceroute时,使用端口33434。

关于python - 为什么我的跟踪路由在运行过程中无法联系服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com