I have a long(ish) set of rules in my routing table, and a list of ip addresses. I'm looking to end up with output like CSV data, with the first column being the ip addresses from the original list, the second column being the gateway that would be used to connect to that IP based on the rules currently in the routing table, and the third column being the device that would be used to connect.

I did think briefly about throwing together a script to get the routing data from route -n and do this, but partway through thinking up a function to do the subnet math I couldn't help thinking that this particular wheel has probably already been invented and is out there somewhere.

Does anyone know what commands could do what I'm after?


You can use ip route get to figure out how your machine would route to an IP. So if you have a list of IPs in a file, one per line you could do

while read -r addr; do
    gw="$(ip route get "$addr" | awk '/via/ {print $3}')"
    if [[ -z $gw ]]; then
         printf 'No route for %s\n' "$addr" >&2
         printf '%s,%s\n' "$addr" "$gw"
done < ip_list

Oops, I forgot to include the dev for you, so here's a solution for that

while read -r addr; do
    ip route get "$addr" | awk -va="$addr" '/via/ {print a "," $3 "," $5} $2 == "dev" {print a ",," $3}'
done < ip_list
  • Thankyou - I was basically just after the "ip route get" part and was planning on doing the rest with cut or something, but what you've got here is much more elegant. Much appreciated. – Blair Sep 20 '16 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.