The most direct way to get your public IP is - as you suggested - access a website that will return this information to you. If there are no drawbacks, why not your own website / application?
But if you need an external service, there are several that you choose - not all so simple to use and / or free (whatismyip.com for example has an API, but only for a paid plan, and with requests limit daily). Here are some options , the simplest and "no frills" being the icanhazip.com (or canihazip.com/s ) - it returns you IP and ready, without html
, body
, or anything! So to access it just do:
URL url = new URL("http://icanhazip.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ip = in.readLine();
in.close();
Maybe it's interesting - if your primary source is offline - try some alternative sources. Others that return the raw IP are ifconfig.me/ip and the ipinfo.io/ip (same procedure above).
Source: this question in SOen