0

I have a router, and when I ask my IP address with this command: InetAddress.getLocalHost().getHostAddress(); then I got my inner IP address. When I step into the www.whatismyip.com page on web then I got an other IP address and that is my real address.

How I ask in Java this real IP address?

Thanks...

Mr. Brooks
  • 33
  • 1
  • 8

2 Answers2

0
    public class IP {

  public String myOuterIP() {
    return(readIP("http://checkip.amazonaws.com"));
  }

  public String readIP(String url) {
    String ip = "";
    try {
      URL whatIsMyIP = new URL(url);
      InputStreamReader ir =new InputStreamReader(whatIsMyIP.openStream());
      BufferedReader in = new BufferedReader(ir);
      ip = in.readLine();
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException");
    } catch (MalformedURLException e) {
      System.out.println("MalformedURLException");
    } catch (IOException e) {
      System.out.println("IOException");
    }
    return ip;
  }
}

This is my result and its working. There is an address on the net:http://checkip.amazonaws.com This was a result for me.

Mr. Brooks
  • 33
  • 1
  • 8
-1

Maybe smth like this?

import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;


URL url = new URL("http://myexternalip.com/raw");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

String externalIP = IOUtils.toString(in, "UTF-8");
  • Hi, Where it is from that import: org.apache.commons.io.IOUtils; ? That is unknown for my Java. – Mr. Brooks Apr 17 '17 at 20:03
  • Open "Project structure", then choose your module (for example app in Android Studio), then choose "Dependencies" and press on a plus button. Choose library dependency. After it type "org.apache.commons.io" in a search field and add "org.apache.directory.studio:org.apache.commons.io:2.4" or smth like this, usually it the first in the list. – Никита Пушнов Apr 17 '17 at 21:21
  • And I have the same question: why do you need your external IP? Because of NAT and some other things you wan't be able to send message end-to-end without any server. – Никита Пушнов Apr 17 '17 at 21:27
  • There is another way to get string with IP from InputStream. [Here](http://stackoverflow.com/questions/18023221/getting-external-ip-address-with-java?rq=1) a little bit more information. – Никита Пушнов Apr 17 '17 at 21:33