0

so I have an app that is running and on startup, I would like to be able to Get the IP address and display it as a String. I have been using the code below.

String ipAddress = "";
try{
   ipAddress = Inet4Address.getLocalHost().getHostAddress();
}
catch(Exception e){
   ipAddress = "IP address Cant be used";
}

every time this is run it will return "IP address Cant be used" so it's throwing an error.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

0

If you are looking to get your public facing IP check out this answer. In short you cannot get your public facing IP because the Network Address Transation does not happen in your Kernel, i.e you dont assign your IP to yourself rather it will be given to you thanks to NAT and DHCP. The following code makes a request to amazons's aws IP API, to retrieve your IP

public static String getIp() throws Exception {
    URL whatismyip = new URL("http://checkip.amazonaws.com");
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));
        String ip = in.readLine();
        return ip;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
martinomburajr
  • 1,235
  • 14
  • 29