Last active
April 16, 2024 15:42
-
-
Save gonoph/539654bf1665390b5e9ddf7396e6f2b6 to your computer and use it in GitHub Desktop.
Different script methods to obtain the primary interface ip address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
### Use any of the following to programmatically obtain the primary interface ip address | |
### | |
# using ansible facts module | |
# requires: jq | |
ansible -msetup -i localhost, all -o | cut -d'>' -f 2- | jq .ansible_facts.ansible_default_ipv4.address | xargs echo | |
# ip command and bash | |
# requires: iproute | |
(set $(ip addr show dev $(set $(ip route | grep default);echo $5) | grep inet | grep -v inet6);echo $2) | cut -d/ -f 1 | |
# ip command, bash, and read instead of set | |
# this is more friendly when the output of any | |
# of the commands are empty | |
IFS=/ read IP MASK <<< $(read T1 IP T2 <<< $(ip addr show dev $(read T1 T2 T3 T4 DEV T5 <<< $(ip route | grep default) ; echo $DEV) | grep inet | grep -v inet6);echo $IP);echo $IP | |
# python-ish | |
# requires: python3.8+ | |
# requires: public network access | |
# requires: access to google's ip: 8.8.8.8 | |
python3 <<< 'import socket as ss | |
with ss.socket(ss.AF_INET, ss.SOCK_DGRAM) as s: | |
s.connect(("8.8.8.8", 80));print(s.getsockname()[0]);' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment