package com.ruoyi.common.utils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; public class IPUtils { public static String getIp() { try { // 获取所有网络接口 Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); // 获取每个网络接口的所有IP地址 Enumeration inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); // 打印IP地址 System.out.println("IP address: " + inetAddress.getHostAddress()); return inetAddress.getHostAddress(); } } } catch (SocketException e) { e.printStackTrace(); } return null; } public static String getIp2() { try { // 获取本地主机 InetAddress localhost = InetAddress.getLocalHost(); System.out.println("本机名称: " + localhost.getHostName()); System.out.println("本机 IP 地址: " + localhost.getHostAddress()); // 获取所有与本地主机关联的 IP 地址 InetAddress[] allLocalAddresses = InetAddress.getAllByName(localhost.getHostName()); for (InetAddress address : allLocalAddresses) { System.out.println("本机所有 IP 地址: " + address.getHostAddress()); return address.getHostAddress(); } } catch (UnknownHostException e) { e.printStackTrace(); } return null; } }