一、查看自身ip
linux的cmd窗口输入 ifconfig
windows的终端输入 ipconfig
java代码:
public static String getIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e);
}
return "";
}
二、查看出口ip,也就是外网ip
curl ifconfig.me
curl ipinfo.io/ip
curl ip.sb
curl icanhazip.com
curl http://icanhazip.com
curl http://ip.3322.net
curl https://httpbin.org/ip
curl -s http://httpbin.org/ip
都是通过curl的方式windows以及linux都适应
java代码:
public static String getExternalIP() {
String ipServiceUrl = "http://api.ipify.org";
try {
URL url = new URL(ipServiceUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String ip = in.readLine();
in.close();
return ip;
} else {
System.out.println("IP地址获取失败");
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}