Spring 获取客户端请求 IP,详见:/NRlovestudy/article/details/90900925
本文获取的是 项目所在系统的IP(本地IP)
本地IP分为两个:局域网IP 和 公网IP 。下面是具体的代码实现(Windows 和 Linux 均适用)。
1、获取局域网IP
//这个方法有局限性 对于本系统自身 只能获取内网IP 本地测试用 // 实际Linux系统 可改用下面那个方法,执行 curl 命令来获取public static String getIpAddress() {try {Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();InetAddress ip = null;while (allNetInterfaces.hasMoreElements()) {NetworkInterface netInterface = (NetworkInterface) 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.toString());}return "";}
2、获取公网IP
参考:/webnote/p/5757435.html
Java执行curl命令
//执行 curl 命令//执行 curl 命令,可获取公网IPpublic static String execCurl(String[] cmds) {ProcessBuilder process = new ProcessBuilder(cmds);Process p;try {p = process.start();BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));StringBuilder builder = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {builder.append(line);builder.append(System.getProperty("line.separator"));}return builder.toString();} catch (IOException e) {System.out.print("error");e.printStackTrace();}return null;}
调用代码:
String[] cmds={"curl",""};//必须分开写,不能有空格String localIP = IPUtil.execCurl(cmds).trim();