How can I find which interface a connection to a given host will be routed through?

烂漫一生 提交于 2019-12-06 12:28:35

问题


My script needs configure SNMP trap destinations for a number of hosts which exist different networks. It is therefor important that the trap destination address is of the interface that is accessible to the remote node.

I don't really want to parse the linux kernel routing table as it's likely to be fragile and break easily. Is there anyway to interrogate the kernel and get it to tell me which way a packet would be routed.

Ideally there would be a python solution for this. I've been looking at the python bindings for libdnet but that only seems to be able to return the default gateway for the address 0.0.0.0.


回答1:


The best answer for this in all scenarios is given by the Linux command ip route get $DEST. This takes into account policy routing (multiple routing tables selected by different selectors).

Syntax (from ip route help):

       ip route get ADDRESS [ from ADDRESS iif STRING ]
                        [ oif STRING ]  [ tos TOS ]



回答2:


A packet is always going to take the most specific route. Assuming your host is not participating in routing, if there are not any statically configured host routes telling traffic destined to a specific network to take a different route, it will always take the default route (aka 0.0.0.0).

Even if you have a separate interface configured on a separate network (e.g. eth1), you can still only have one default route. If you need to certain destinations to take eth1, then you will need to configure a static route (aka host route).

Have you done this? If not, that is why libdnet is only providing the default gateway, because that's the only way out that the host knows.



来源:https://stackoverflow.com/questions/5556373/how-can-i-find-which-interface-a-connection-to-a-given-host-will-be-routed-throu

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