Java IP Address Get getIp()

Here you can find the source of getIp()

Description

Returns the public IP if one isn't specified in the machine.ip System property

License

Open Source License

Exception

Parameter Description
IOException thrown if connection to third party service failed

Return

IP address if found, null otherwise

Declaration

public static String getIp() throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    private static final String IP_PROVIDER = "https://api.ipify.org/";

    /**/*from  w  ww  .j a v  a 2 s. c  o  m*/
     * Returns the public IP if one isn't specified in the <i>machine.ip</i> System property
     *
     * @return IP address if found, null otherwise
     * @throws IOException thrown if connection to third party service failed
     */
    public static String getIp() throws IOException {
        if (System.getProperty("machine.ip") != null) {
            return System.getProperty("machine.ip");
        }
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new URL(IP_PROVIDER).openConnection().getInputStream()))) {
            String ip;
            if ((ip = br.readLine()) != null) {
                return ip;
            }
        }
        return null;
    }
}

Related

  1. getIp()
  2. getIp()
  3. getIp()
  4. getIp()
  5. getIP()
  6. getIP()
  7. getIp()
  8. getIpAddress()
  9. getIPAddress()