Python find first network hop

女生的网名这么多〃 提交于 2020-01-24 19:31:09

问题


I need to find the first network hop is in a python program on Linux. I can't just depend on the default gateway being the first hop, because some of the network software on the box may (or may not) insert catch all routes:

0.0.0.0/1
128.0.0.0/1

I've thought about popen'ing a tracepath -m 1 <some ip> and parsing the output, but I dislike depending on the format of the output of another program. Reading the routing table from /proc and applying routing logic to it I think is a little beyond my scripting abilities, though I will likely try it at some point. Is there a an easier way (has someone else already invented-this-wheel in a module I'm not aware of)?


回答1:


What do the "catch all" routes do? If they are simply gateway routes, doing a route lookup would still work. You can do something like:

$ ip route get <ip> | head -1 | awk '{ print $3 }'

This would print the gateway address for an off-link route:

$ ip route get 8.8.8.8 | head -1 | awk '{ print $3 }'
192.168.0.1

... or the interface name for an on-link route:

$ ip route get 192.168.0.2 | head -1 | awk '{ print $3 }'
eth0

And by the way (as my answer implies) I agree with the comment that the principle of not relying on an external program is overcautious in this case. =) I doubt that the output of ip will change.

Personally I'd use the route lookup since tracepath or traceroute would rely on the 1st hop host actually sending you the TTL expired ICMP message (it might drop it). I don't know what your use case is though.

If you need a python library to do this, I'd look into libdnet.



来源:https://stackoverflow.com/questions/4953629/python-find-first-network-hop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!