How to check external IP address

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

Effortless but insecure solution

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

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

Robust and secure solution

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

This idea uses secure key based solution introduced in How to create persistent reverse SSH tunnel blog post.

First step

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

$ cat << EOF | sudo tee /usr/bin/ssh_client_ip.sh
#!/bin/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}'
EOF

$ 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 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 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"

Now you can remove uploaded public key.

Fifth step

Now you can check your external IP address using created SSH key.

$ ssh -q -i .ssh/checkip checkip@remote_server
91.38.141.221
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu