Obtaining your public IP Address from the command line

Obtaining your public IP Address from the command line

Most command line users, even the newbies, will have see the use of ipconfig for reading details of network interfeaces and their respective configuration. However, the configuration of most devices only applies to the connection to the internal network. If you need to know the IP Address of your external (public facing) internet gateway, you'll need to do a little more work.

Sure there are plenty of webistes that can give you this information (even our website has a tool: https://neurotechnics.com/tools/ipinfo). And searching google for the phrase what is my ip address will give you the answer as a google information card (along with about 1.8 trillion other results).

DOS / Bash (Windows and Linux)

From the Command Prompt (or within a batch/cmd script) you can use the built-in nslookup command:

nslookup myip.opendns.com resolver1.opendns.com

However, this is a little more verbose than need in an automation context.
To simplify, we probably need to parse the output, which in abatch file can be tedious. So, lets use CURL to call a remote API. (** Yes, curl should work out of the box in recent versions of windows).

We can talk to various web-api's for this... ipinfo.io and ifconfig.me are the two I use interchangeably.

C:\> curl https://ipinfo.io/ip

C:\>curl https://ifconfig.me/ip

PowerShell (Windows and Linux)

If you prefer using PowerShell, you can use Invoke-WebRequest to call one of the many remote websites or API's that will give you the information you need:

PS> Invoke-WebRequest ifconfig.me/ip

The Invoke-WebRequest command will return a formatted PowerShell output containing a summary of the http-response from the server.

The Content property contains the information we're interested in. You can use the response data as is, or you can retrieve the Content property only, by specifying the command line:

PS C:\> (Invoke-WebRequest ifconfig.me/ip).Content
PS C:\>