public String getIPAddress(){
try {
URL url = new URL("http://checkip.amazonaws.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String ip = br.readLine().trim();
System.out.println("Public IP Address: " + ip);
return ip;
} catch (Exception e) {
System.out.println("Error in getting public IP address, trying to get local IP address.");
try {
String localIP = getLocalIP();
System.out.println("Local IP Address: " + localIP);
} catch (SocketException se) {
System.out.println("Error in getting local IP address: " + se.getMessage());
}
}
return null;
}
private static String getLocalIP() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
return null;
}
无网络环境则获取内网地址