How can I get the list of all active network interfaces programmatically?
Solution 1:
There may be several different ways to accomplish what you're asking, however, I'll just throw this out there.
I have a MacBook Pro that doesn't have a built-in Ethernet Port so in my examples I'll use Hardware Port: Wi-Fi since I tested this in both examples below and it worked, however you can change it to Hardware Port: Ethernet if that is what the output of networksetup -listallhardwareports
shows for you.
If you just want to output the target device's IP Address to stdout
, use the following example:
$ ipconfig getifaddr $(networksetup -listallhardwareports | awk '/Hardware Port: Wi-Fi/{getline; print $2}')
192.168.1.100
If you want to assign it to a variable in a script, use the following example:
ipAddress="$(ipconfig getifaddr $(networksetup -listallhardwareports | awk '/Hardware Port: Wi-Fi/{getline; print $2}'))"
Explanation:
The relevant output of networksetup -listallhardwareports
for my system is:
Hardware Port: Wi-Fi
Device: en0
Ethernet Address: 28:cf:e3:10:a4:cd
(Note: That is not my real MAC Address)
Using $(...)
command substitution in order to have something to pass to ipconfig getifaddr <args>
I determine the Hardware Port's Device Name with the output of networksetup -listallhardwareports
and pipe |
it through awk
which is looking for Hardware Port: Wi-Fi
and uses the get line
function, which reads the next line after the match and is passed to print $2
, which in essence prints the second part of the line following the match, which in the case is en0
and that gets passed to ipconfig getifaddr
as its argument in the first example, e.g ipconfig getifaddr en0
. The output of which is the IP Address.
In the second example a second $(...)
command substitution is used around the complex command line used for the stdout
example to assign it to the ipAddress
variable when used in a script.
Note: This is really meant to be an example as I've not coded it to account for the device being down. In other words if the device doesn't have and IP Address there will be no output to stdout
and nothing assigned to the ipAddress
variable in the script. Although in the script it can be coded to test whether or not the ipAddress
variable is empty and act accordingly.