lazy/files/zsh/50-function.zsh
2023-11-30 12:06:25 +08:00

55 lines
1.9 KiB
Bash

#!/bin/zsh
__zsh_is_public_ipv4() {
local ip=$1
if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
IFS='.' read -r -A ADDR <<< "$ip"
if [[ ${ADDR[1]} -eq 10 ]]; then
return 1
elif [[ ${ADDR[1]} -eq 172 && ${ADDR[2]} -ge 16 && ${ADDR[2]} -le 31 ]]; then
return 1
elif [[ ${ADDR[1]} -eq 192 && ${ADDR[2]} -eq 168 ]]; then
return 1
else
return 0
fi
else
return 1
fi
}
__zsh_get_ipv4() {
local ipv4=$(ip route get 1.1.1.1 | head -1 | awk '{print $7}')
if __zsh_is_public_ipv4 $ipv4; then echo "$ipv4"; return 0; fi
ipv4=$(ip route get 1.1.1.1 | head -1 | awk '{print $NF}')
if __zsh_is_public_ipv4 $ipv4; then echo "$ipv4"; return 0; fi
ipv4=$(curl -4 -s ifconfig.me)
if __zsh_is_public_ipv4 $ipv4; then echo "$ipv4"; return 0; fi
ipv4=$(host -4 myip.opendns.com resolver1.opendns.com | grep "myip.opendns.com has" | awk '{print $4}')
if __zsh_is_public_ipv4 $ipv4; then echo "$ipv4"; return 0; fi
# echo "No public IPv4 address found"
return 1
}
__zsh_get_ipv6() {
if [[ "$(ip -6 route get 2001:4860:4860::8888 2>&1 | awk '{print $NF}')" == "unreachable" ]]; then
echo "No IPv6 connectivity"
return 1
fi
local ipv6=$(ip route get 2001:4860:4860::8888 | head -1 | awk '{print $11}')
if [[ $ipv6 =~ ^([0-9a-fA-F]{0,4}:){7}[0-9a-fA-F]{0,4}$ ]]; then echo "$ipv6"; return 0; fi
ipv6=$(ip route get 2001:4860:4860::8888 | head -1 | awk '{print $NF}')
if [[ $ipv6 =~ ^([0-9a-fA-F]{0,4}:){7}[0-9a-fA-F]{0,4}$ ]]; then echo "$ipv6"; return 0; fi
ipv6=$(curl -6 -s ifconfig.me)
if [[ $ipv6 =~ ^([0-9a-fA-F]{0,4}:){7}[0-9a-fA-F]{0,4}$ ]]; then echo "$ipv6"; return 0; fi
# echo "No public IPv6 address found"
return 1
}
__zsh_get_ip() {
__zsh_get_ipv4
__zsh_get_ipv6
}
alias net='__zsh_get_ip'