开发者

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

开发者 https://www.devze.com 2023-02-22 11:52 出处:网络
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

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 ther开发者_StackOverflow社区e 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.


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 ]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号