#bashscripting nugget:

When we have multiple network interfaces, how do we quickly determine (1) what interface we are using to reach the internet (or that network), (2) what the IP address is for that interface, and (3) what our subnet masking is, using the fewest lines of code possible?

Well, the problem starts in determining how we are reaching the internet (or any specific network).

Yes, we could assume the device is using the default set on our route, but assumptions quickly lead to problems.

We can, instead of assuming, test to see exactly which interface the traffic bound for a specific destination is taking:

nicAddress=$( ip route get $(getent ahosts “8.8.8.8” | awk ‘{print $1; exit}’) | \ grep -Po ‘(?<=(dev )).*(?= src| proto)’ )

Once we have determined which interface we are using to access that network, we will then pull our IP and netmask.

tempIP=$(ip address | grep $nicAddress | tail -1 | cut -d ‘ ‘ -f 6 | sed ‘s/\// /’) ipAddress=$(echo $tempIP | cut -d ‘ ‘ -f 1) whackMask=$(echo $tempIP | cut -d ‘ ‘ -f 2)

And, now we can print it out in a pretty format:

printf ‘%s %s\n’ ‘We are reaching the internet via interface’ $nicAddress ‘using network IP ‘ $ipAddress ‘and /’$whackMask’ masking.’

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>