get Current IP Address via web service - Java Network

Java examples for Network:IP Address

Description

get Current IP Address via web service

Demo Code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main{
    public static void main(String[] argv) throws Exception{
        System.out.println(getCurrentIPAddress());
    }//from w ww  . ja v  a 2 s  .  c o  m
    private static final String PUBLIC_ADDRESS_URL = "http://ipinfo.io/ip";
    private static String ipAddress;
    public static String getCurrentIPAddress()
            throws CantGetCurrentIPAddressException {

        if (ipAddress != null)
            return ipAddress;

        HttpURLConnection conn = null;
        try {

            conn = (HttpURLConnection) new URL(PUBLIC_ADDRESS_URL)
                    .openConnection();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String response = reader.readLine();

            if (conn.getResponseCode() == 200) {
                ipAddress = response.trim();
                return ipAddress;
            } else
                throw new CantGetCurrentIPAddressException(null, "",
                        "We couldn't find out the ip address.");

        } catch (IOException ioException) {

            throw new CantGetCurrentIPAddressException(ioException, "",
                    "There was an error trying to get the ip address from the site: "
                            + PUBLIC_ADDRESS_URL);
        } finally {

            if (conn != null)
                conn.disconnect();
        }

    }
}

Related Tutorials