-4

I use this code to get my current IP:

public String getIpAddress() throws NullPointerException,
        MalformedURLException, IOException {
    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();
            }
        }
    }

}

but the return value is incorrect. how to get the IP properly

  • 7
    **How** doesn't it work? Does it explode? – SLaks Apr 06 '14 at 18:18
  • What do you call your "current IP" anyway? It is a vague notion. `ip addr` will show all my IP addresses on my system. – fge Apr 06 '14 at 18:19
  • I'm not a Java programmer, but this does not look like "getting the IP" at all. You are reading web site contents from a URL. So what do you actually want? If you indeed want the current IP use http://stackoverflow.com/questions/9481865/how-to-get-ip-address-of-current-machine-using-java – Jan Doggen Aug 08 '14 at 17:14
  • i can't post more quetions on this site by above question please.. i am poor in english.. here after i post clear question. please remove the badges for this question.. i don't know how to improve this question...pls – Prakash Selvam Sep 16 '14 at 09:21

1 Answers1

1

You can use Will's code on this Thread : Getting the 'external' IP address in Java

He use Amazon service to get his "external IP".

Here his code :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class IpChecker {

    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();
                }
            }
        }
    }
}

All credits goes to Will.

Community
  • 1
  • 1
Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59