API call to get interface IP address

Started by tgice, May 25, 2023, 01:08:09 AM

Previous topic - Next topic
May 25, 2023, 01:08:09 AM Last Edit: May 25, 2023, 01:15:11 AM by tgice
Hi, first time posting in this forum, and I really wanted to just post a solution to this 4 year old post, but could not seem to do that (possibly because it's archived?):

https://forum.opnsense.org/index.php?topic=12127.0

I was trying to find a local alternative to picking up my WAN IP address (for when it changes with my cable modem connection) short of using ipinfo like this:

curl https://ipinfo.io/ip

which works fine, but again, OPNSense of course knows what the WAN IP is, and it'd be nice to just grab it locally without bothering someone else's servers.

Like the two people in the above thread, I was unable to quickly find the solution in OPNSense APIs but finally did, so thought I'd share it for others looking for the same thing.

NOTE: I also used the jq project utility from GitHub to neatly parse the JSON, which was a big help:

https://stedolan.github.io/jq/

curl -k -u "%key%":"%secret%" https://your-opnsense-server/api/diagnostics/interface/getinterfaceconfig | jq -r ".em1.ipv4[0].ipaddr"

I'm doing this in Windows, so you just set the key & secret environment variables first (you of course need to have added an API key set to a user first).

Also note, the first term in the jq filter (em1 here) is the interface you're targeting.