How To Get Your External/Public IP With Powershell Core Using A RestAPI

How many times we need to gather simple informations manually? Wouldn’t be easier and simpler just to get it with a one-liner? Every user can get his your public ip opening a browser and typing “What is my ip?”, few users know how to get the same information in one line from the cli.

Using Curl

A very popular BaSH command is curl, recently available on Windows 10 (1803) cmd-prompt :

As you can see is just one line. But we need curl to get that information? No we can use Powershell, if we use PowerShell Core we will be sure to get the same result on each OS.

Using PowerShell

We will use Invoke-RestMethod, which is included from PowerShell 3, we will connect to 3 public websites to compare the results and in the last example most importantly we can retrieve a JSON object that we can use or simply save.
The first website is icanhazip.com, it’s a funny name and it’s always easy to remember, at least for me

The second one is the www.ipify.org, it’s a Simple Public Address API.

The last one that I use is www.ipinfo.io :

Selecting just the IP:

Invoke-RestMethod and JSON objects

Using a RestAPI and storing the JSON object on a text file on a local directory.

In case you want a similar result of the curl example, using the Invoke-RestMethod alias will be ever more compact:

Do you need IPv4 and/or IPv6?

I suggest you to use icanhazip, with 2 subdomains ipv4 and ipv6

Quick Update

 

  • On this subject, just a few months ago I’ve created my personal URL shortener called JSYK.IT (which is a simple acronym – Just So You Know IT) and if you want to obtain your public IP you can just type /IP:  https://jsyk.it/ip 
If you view the source code of the webpage contains just your IP v4 address so it’s ideal for scripts or queries from the command line.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.