I am constantly on the move, so sometimes I need to quickly verify my external IP address, as I do not want to accidentally block myself on some kind of firewall.

The effortless solution

The easiest way to check an external IP address is to use ifconfig.me or ipinfo.io service.

$ curl ifconfig.me/ip
$ curl ipinfo.io/ip

The robust and secure solution

The better solution is to use a shell script to get an external IP address from a private remote server over the secure SSH protocol.

This idea uses a secure key based solution introduced in Creating persistent reverse SSH tunnel blog post.

First step

Create a simple shell script on the remote server that will print the connected user’s IP address.

$ cat << EOF | sudo tee /usr/bin/ssh_client_ip.sh
# this shell script should be executed over SSH connection
# to print IP address of the connected user

who am i --ips | awk '{print \$NF}'
$ sudo chmod +x /usr/bin/ssh_client_ip.sh

Second step

Connect to remote server and create checkip user.

$ sudo useradd -m checkip

Third step

Create SSH key pair on the local machine.

$ ssh-keygen -q -N "" -f ~/.ssh/checkip

Fourth step

Upload ~/.ssh/checkip.pub file to the remote server and perform the following operations while still being connected to it.

Create a missing .ssh directory.

$ sudo su -s /bin/sh checkip -c "mkdir ~/.ssh"

Add uploaded public key to the pool of keys authorized for authentication.

$ echo 'command="/usr/bin/ssh_client_ip.sh",no-agent-forwarding,no-port-forwarding,no-user-rc,no-X11-forwarding' $(cat checkip.pub) | sudo su checkip -c "tee >> ~/.ssh/authorized_keys"

Fifth step

Now you can check your external IP address using the prepared solution.

$ ssh -q -i .ssh/checkip checkip@remote_server