dotfiles/bin/myip
Akemi Izuko de244f9ea7
Init again
The dotfiles are back
2023-12-23 20:13:47 -07:00

68 lines
1.6 KiB
Bash
Executable file

#!/bin/bash
# List system's WAN and LAN ip addresses
# Depends on ifconfig and awk
if [[ $1 =~ '-h' ]]; then
cat <<EOF
List the system's WAN and LAN addresses
USAGE:
$(basename "$0")
EOF
exit 0
fi
awk_lan () {
awk '
BEGIN { print "Local:" }
/UP/ {
split($0, info, /:/)
device_name = '"$1"'
is_up = 1
}
match($0, /inet ([0-9]{1,3}\.){3}[0-9]{1,3}(\/[0-9]{1,3})? /) {
if (is_up) {
ip_addr = substr($0, RSTART + 5, RLENGTH - 5)
printf(" %s: %s\n", device_name, ip_addr)
is_up = 0
}
}' -
}
# List all possible inet addresses
if command -v ip address &> /dev/null; then
ip address | awk_lan 'substr(info[2], 2)'
elif command -v ifconfig &> /dev/null; then
ifconfig | awk_lan 'info[1]'
else
echo '`ifconfig` not found'
fi
# Print network's public IP address
if command -v dig &> /dev/null; then
public_ip=$(dig +short myip.opendns.com @resolver2.opendns.com)
elif command -v host &> /dev/null; then
public_ip=$(host myip.opendns.com resolver1.opendns.com)
fi
# Backup address fetching. Slower though more reliable
if [[ -z $public_ip ]]; then
if command -v curl &> /dev/null; then
public_ip=$(curl --silent https://ifconfig.me/ip)
elif command -v wget &> /dev/null; then
public_ip=$(wget --quiet -O - https://ifconfig.me/ip)
fi
fi
if [[ -n $public_ip ]]; then
echo "$public_ip" | awk ' match($0, /([0-9]{1,3}\.){3}[0-9]{1,3}$/) {
printf("Public (WAN): %s\n", substr($0, RSTART, RLENGTH))
}'
else
echo 'Public IP not found'
fi