Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 673
hockey_dave Avatar asked Dec 28 '22 01:12

hockey_dave


1 Answers

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;
    }
}
like image 156
Matt MacLean Avatar answered Jan 06 '23 11:01

Matt MacLean