The most direct way to get your public IP is - as you yourself suggested - to access a website that will return that information to you. If there are no drawbacks, why not your own website/application?
But if you need an external service, there are several 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 limit of daily requests). Here are some options, the simplest and "no frills" is the hazicanip.com (or canihazip.com/s) - it returns you the IP and ready, without html
, body
, or nothing! 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 - in case your main source is offline - try some alternative sources. Others that return the "raw" IP are the ifconfig.me/ip and the ipinfo.io/ip (same procedure above).
Source: that question on Soen
What is the difference of this question to your previous question?
– bfavaretto
the difference is that the previous question captures ip with a socket connection. this question, needs a method for capturing ip before any connection
– user17270
And here, it would be http?
– bfavaretto
I thought to put in the program something like accessing a site whatismyip for example and store the result in some variable, but I’m having problems for this : (
– user17270
Do you want this IP to be obtained from the client itself, or from the server when contacted by a client? Your last comment suggests that it is something that does not involve the server in any way. Could you give more details than you intend to do? (feel free to [Dit] the question as necessary)
– mgibsonbr
@mgibsonbr changed the question, I hope it is more enlightening. :)
– user17270