Java IP Address Get getIp()

Here you can find the source of getIp()

Description

get Ip

License

Open Source License

Return

This machine's external ip address(or local, if the external could not be determined)

Declaration

public static final String getIp() 

Method Source Code


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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;

import java.net.URL;
import java.net.UnknownHostException;

public class Main {
    private static String ipAddress = null;

    /** @return This machine's external ip address(or local, if the external
     *         could// w w  w. j  a v  a2  s  .  com
     *         not be determined) */
    public static final String getIp() {
        if (ipAddress == null) {
            try {
                URL whatismyip = new URL("http://checkip.amazonaws.com");
                try (BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()))) {
                    ipAddress = in.readLine();
                }
            } catch (Throwable e) {
                System.err.println("Unable to retrieve this machine's external ip: " + e.getMessage());//PrintUtil.printThrowable(e);
                try {
                    ipAddress = InetAddress.getLocalHost().toString();
                } catch (UnknownHostException e1) {
                    ipAddress = "";
                }
            }
        }
        if (ipAddress == null) {
            ipAddress = "";
        }
        return ipAddress;
    }
}

Related

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