On reboot, the IP address of an amazon instance changes. How to find the new IP address using java API?
In order to fetch the public IP of the instance you first need to get the instance id of that instance. You can get the instance id of the instance by using the following java code.
List instances = runInstancesResult.getReservation().getInstances();
String instanceId = instances.get(0).toString().substring(13, 23);
And now in order to get the public IP you can use the following java code.
public void fetchInstancePublicIP() {
DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds("i-d99ae7d2");
DescribeInstancesResult result= ec2.describeInstances(request);
List list = result.getReservations();
for (Reservation res:list) {
List instanceList= res.getInstances();
for (Instance instance:instanceList){
System.out.println("Public IP :" + instance.getPublicIpAddress());
System.out.println("Public DNS :" + instance.getPublicDnsName());
System.out.println("Instance State :" + instance.getState());
System.out.println("Instance TAGS :" + instance.getTags());
}
}
}