30

On a multihomed Linux machine, how can I find out what network interface will be used to send a packet to a specific host? I need to do this programmatically and I'd rather not parse and interpret the routing table myself.

Rob H
  • 629
  • 1
  • 7
  • 15

3 Answers3

51

Use ip route for this. For instance:

ip route show to match 198.252.206.16
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
34

Shorter option:

ip route get 172.29.42.94
davidparks21
  • 928
  • 1
  • 12
  • 27
Alexey
  • 347
  • 3
  • 2
7

Yes, as Michael Hampton suggests, use ip route. If you only want the interface, use this

ip -o route get $ip | perl -nle 'if ( /dev\s+(\S+)/ ) {print $1}'

For example:

# ip=8.8.8.8
# iface=$( ip -o route get $ip | perl -nle 'if ( /dev\s+(\S+)/ ) {print $1}' )
# echo $iface
eth1
mivk
  • 4,004
  • 3
  • 37
  • 32