hockey_dave
hockey_dave

Reputation: 584

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?

Upvotes: 4

Views: 3154

Answers (3)

Ignacio A. Poletti
Ignacio A. Poletti

Reputation: 616

Alternative (not clearest solution), might be request an external service like this to know your public IP. http://whatismyip.org/

EDIT: I found a nice service that returns json or text format. https://www.ipify.org/

Upvotes: 2

Matt MacLean
Matt MacLean

Reputation: 19648

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

Upvotes: 7

aviad
aviad

Reputation: 8278

You can call DescribeInstances - it returns a bunch of information including Public IP Address (ip-address filter).

...
DescribeInstancesRequest dis = new DescribeInstancesRequest();   
DescribeInstancesResult disresult = ec2.describeInstances(dis);
...

Upvotes: 1

Related Questions