Java program to find the IP Address


Following are some of the top services that provide your public IP address

http://checkip.amazonaws.com

http://icanhazip.com/

http://myip.dnsomatic.com/

When you are writing a program to find the IP Address it's always better to use more than one service, So that even one of the services are down your program still runs.
Following is the Java program which uses the listed services and finds out your IP address. It automatically switches between services based on their availability i.e if the first service fails it automatically switches to the next one.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class WhatsMyIp {

	static List<String> providers = new ArrayList<>();

	static {
		providers.add("http://checkip.amazonaws.com");
		providers.add("http://icanhazip.com/");
		providers.add("http://myip.dnsomatic.com/");
	}

	public static void main(String[] args) throws MalformedURLException, IOException {
		String ip = null;
		for (String provider : providers) {
			ip = getPublicIP(provider);
			if (ip != null && !ip.isEmpty()) {
				break;
			}
		}

		System.out.println(ip);

	}

	private static String getPublicIP(String provider) {
		String ip = null;
		try {
			URL url = new URL(provider);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			ip = br.readLine();
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println("Unable to fetch with provider:" + provider);
		}
		return ip;
	}

}

Output:

123.45.xx.xxx