描述
get Current IP Address via web service
例子
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 w w .2 1 d o c. n et
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();
}
}
}