如果在Windows系统环境下,当然可以直接通过InetAddress.getLocalHost()方法直接获取。
import java.net.InetAddress;
public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}
运行结果是:
Local HostAddress: 169.254.52.252 Local host name: LAPTOP-RV008F14
但是上述获取ip的方式有时候会得到127.0.0.1
Java提供了一个NetworkInterface类。这个类可以得到本地所有的物理网络接口和虚拟机等软件利用本机的物理网络接口创建的逻辑网络接口,NetworkInterface可以通过getNetworkInterfaces方法来枚举本地所有的网络接口。我们也可以利用getNetworkInterfaces得到网络接口来枚举本机的所有ip地址。
public static EnumerationgetNetworkInterfaces() throws SocketException
getInterfaceAdresses()方法
这个方法用来获取此网络接口的全部或部分InterfaceAddresses的列表。
public ListgetInterfaceAddresses()
写一个获取IP的util类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.util.Enumeration;
import java.util.List;
public class IPHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(IPHelper.class);
private static String hostIp;
static {
String ip = null;
Enumeration allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) allNetInterfaces.nextElement();
//netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp() 用于排除回送接口,非虚拟网卡,未在使用中的网络接口.
if (networkInterface.isLoopback() || networkInterface.isVirtual() || networkInterface.isUp()) {
continue;
}
List interfaceAddresses = networkInterface.getInterfaceAddresses();
for (InterfaceAddress interfaceAddress : interfaceAddresses) {
InetAddress inetAddress = interfaceAddress.getAddress();
if (inetAddress instanceof Inet4Address) {
if (StringUtils.equals(inetAddress.getHostAddress(), "127.0.0.1")) {
continue;
}
ip = inetAddress.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
hostIp = ip;
}
public static String localIp() {
return hostIp;
}
}
本文参考:
https://blog.csdn.net/nianbingsihan/article/details/80265029



