-
Notifications
You must be signed in to change notification settings - Fork 0
/
myip
executable file
·97 lines (92 loc) · 2 KB
/
myip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/sh
# vi:et lbr noet sw=2 ts=2 tw=79 wrap
# Copyright 2022-2024 David Rabkin
# Reports external IP in a loop.
# The script uses local variables which are not POSIX but supported by most
# shells. See:
# https://stackoverflow.com/q/18597697
# shellcheck disable=SC3043 # Uses local variables.
# shellcheck disable=SC1091,SC2034 # File not following, appears unused.
set -- "$@" --quiet
readonly \
BASE_APP_VERSION=0.9.20240121 \
BASE_MIN_VERSION=0.9.20240102
. base.sh
# The index starts with 0, it guarantees the title printing from the begging.
main() {
validate_cmd awk dig whois
chrono_sta run || die
local i=0
while :; do
[ $((i % 24)) -eq 0 ] && title
myip
sleep 5
i=$((i + 1))
done
}
# Prints external IP.
myip() {
local dur ip out state
ip="$(
dig \
-4 \
+short \
myip.opendns.com \
@resolver4.opendns.com \
2>&1
)" || {
loge OpenDNS failed: "$ip"
return 0
}
var_exists ip || {
ip="$(
dig \
-4 \
-t txt \
+short \
o-o.myaddr.l.google.com \
@ns1.google.com \
2>&1
)" || {
loge Google DNS failed: "$ip"
return 0
}
ip="$(printf %s "$ip" | awk -F\" '{print $2}')"
var_exists ip || {
loge OpenDNS and Google DNS failed to resolve my IP
return 0
}
}
out="$(whois "$ip" 2>&1)" || {
loge whois "$ip" failed: "$out"
return 0
}
# At first tries to find a state of a country.
state="$(
printf %s "$out" |
awk -F':[ \t]+' 'tolower($1) ~ /^stateprov$/ {print toupper($2)}' |
head -1
)"
var_exists state || {
state="$(
printf %s "$out" |
awk -F':[ \t]+' 'tolower($1) ~ /^country$/ {print toupper($2)}' |
head -1
)"
var_exists state ||
state=NO
}
dur="$(chrono_get run)" || die
ip="$(printf %15s "$ip")"
tsout "| $ip | $state | $dur"
}
# Prints top title.
title() {
cat <<-EOM
------------------+-----------------+-------+----------------
Timestamp | IP | State | Duration
------------------+-----------------+-------+----------------
EOM
}
# Starting point.
main "$@"