hockey_dave hockey_dave - 2 months ago 9
Java Question

Get Elastic IP from running instance

From a java application running on an EC2 instance, I'd like to know what my own elastic IP address that was manually assigned from the management console. Is there a way to query EC2 API for this?

Answer

If you using a linux ec2 instance this should work:

Command:

curl http://169.254.169.254/latest/meta-data/public-ipv4

Java Code:

public static String getIP() throws IOException, InterruptedException {
    Process p = Runtime.getRuntime().exec("curl http://169.254.169.254/latest/meta-data/public-ipv4");
    int returnCode = p.waitFor();
    if ( returnCode == 0 ) {
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String ip = r.readLine();
        r.close();
        return ip;
    }
    else {
        //handle error
        return null;
    }
}