How can I get the local IP address in macOS to use in a script?
I need to figure out the local IP address of Github runner, which uses macOS 11. I need this for my integration tests.
I tried:
LOCAL_IP=ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'
SERVER_URL="http://${LOCAL_IP}:5000"
However, this gave me just: http://:5000
Which is the correct command for this?
Solution 1:
LOCAL_IP=ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'
sets the variable LOCAL_IP
to ifconfig
to run an empty command, and sends the empty output of that empty command to the pipe built of | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'
. So LOCAL_IP
is never set afterwards.
What you probably want to run is
LOCAL_IP=$(ifconfig | grep 'inet ' | grep -Fv 127.0.0.1 | awk '{print $2}')
which can be simplified to
LOCAL_IP=$(ifconfig | awk '/inet /&&!/127.0.0.1/{print $2})
Unfortunately this will return two rows on Macs which are connected over both Ethernet and WLAN. So it's probably safer to use
LOCAL_IP=$(ifconfig | awk '/inet /&&!/127.0.0.1/{print $2;exit})
which will pick the first network interface/IP address found.
Solution 2:
Here is another option which may be useful to you.
This command will create a variable with the local IP address.
LOCAL_IP=$(osascript -e "IPv4 address of (system info)")
This command will return the local IP address stored in $LOCAL_IP
echo $LOCAL_IP
Solution 3:
The local IP address can be obtained with the following command:
ipconfig getifaddr en0
or en1
, depending on your Mac and your connection.