How To Get Public IP Address In Bash?

Published July 15, 2024

Problem: Obtaining Public IP Address in Bash

Getting your public IP address is often needed for network tasks and setups. While you can find this information on websites, getting it directly from a Bash command line can be more useful and easier to automate.

Step-by-Step Guide to Get Public IP Address

Using curl Command

The curl command is a tool for transferring data using various protocols. To get your public IP address with curl:

  1. Open your terminal.
  2. Type this command:
curl ipinfo.io/ip
  1. Press Enter.

This command sends a request to ipinfo.io and shows only the IP address in the output. The result will be your public IP address, for example:

203.0.113.42

Tip: Customize Your curl Output

You can get more information about your IP address by modifying the curl command. For instance, use curl ipinfo.io to get details like city, region, country, and timezone along with your IP address.

Using wget Command

wget is a command-line tool for retrieving content from web servers. To get your public IP address using wget:

  1. Open your terminal.
  2. Enter this command:
wget -qO- ipinfo.io/ip
  1. Press Enter.

The -qO- options tell wget to work quietly and output the result to the standard output. The command will show your public IP address, similar to the curl method.

Using dig Command

dig (Domain Information Groper) is a network administration command-line tool for querying DNS name servers. To use dig for retrieving your public IP address:

  1. Open your terminal.
  2. Type this command:
dig +short myip.opendns.com @resolver1.opendns.com
  1. Press Enter.

This command queries the OpenDNS server for your public IP address. The output will be your IP address, for example:

203.0.113.42

Example: Using dig with Different DNS Servers

You can use other DNS servers to get your public IP. For example:

dig TXT +short o-o.myaddr.l.google.com @ns1.google.com

This command uses Google's DNS server to retrieve your public IP address.

Each of these methods provides a way to get your public IP address directly from the command line, making it easy to use in scripts or for quick checks.