I wanted to display external/public IP address whenever I open terminal, but also add an alias that will allow me to check my public IP from terminal. Here is how to do it.
Add to your ~./bashrc following lines:
#Show public IP address whatsmyip="$(dig +short myip.opendns.com @resolver1.opendns.com)" echo "Your Public IP is: $whatsmyip" alias whatsmyip="echo 'Your Public IP is: $whatsmyip'"
For ease of use, I stored the output of the command in variable $whatsmyip that I can then make a call to in an alias whatsmyip
Explanation of the command itself
dig (domain information groper) command will query DNS nameserver for information about IP address of given domain. Full syntax for the command is ‘dig name @server type’.
name is the record you want to query
server is the name or IP address of DNS server to query
type is the what type of query you want to look at – it could be ANY, A or MX, if omitted A is used by default
+short is used to get just the answer to the query
So the full command is dig +short myip.opendns.com @resolver1.opendns.com
myip.opendns.com is a special domain that sends back the IP address of where the request came from, meaning your own IP.
@resolver1.opendns.com is the DNS server to query, we could also use the IP address – 126.96.36.199
If we would replace myip.opendns.com with bbc.co.uk we would get IP addresses of that domain.
The use of +short is important as we only want to know the answer to the query to then store it in a Bash variable, without it, full returned query looks like this:
; <<>> DiG 9.11.3-1ubuntu1.3-Ubuntu <<>> myip.opendns.com @resolver1.opendns.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20980 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;myip.opendns.com. IN A ;; ANSWER SECTION: myip.opendns.com. 0 IN A xxx.xxx.xxx.82 ;; Query time: 13 msec ;; SERVER: 188.8.131.52#53(184.108.40.206) ;; WHEN: Fri Jan 18 12:20:47 GMT 2019 ;; MSG SIZE rcvd: 61
Remember to reload bash with source ~/.bashrc
More info on dig command here: https://linux.die.net/man/1/dig
EDIT (21/01/19): If dig command is not available on your system, you will have to install bind-tools.
I’ve used Linux-Mint (based on debian) for this guide which already had bind-tools, but I also use Manjaro (based on Arch) and CentOS, which didn’t have it, so I had to install it separately, via simple command:
Arch – sudo pacman -Syu bind-tools
CentOS – sudo yum install bind-utils
Bind-tools can also be installed Windows OS from here: https://www.isc.org/downloads