Java本机IP获取方法详解
在Java中获取本地IP地址有多种方式,以下是几种常见的方法:
1. 使用 InetAddress
类
InetAddress
类是Java标准库中用于表示IP地址的类,可以通过它获取本地主机的IP地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2. 使用 NetworkInterface
类
NetworkInterface
类提供了更细粒度的网络接口信息,可以获取所有网络接口的IP地址。
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) {
try {
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.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
System.out.println("Local IP Address: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
3. 使用第三方库(如 Apache Commons Net
)
如果你需要更复杂的功能,可以使用第三方库,如 Apache Commons Net
。
import org.apache.commons.net.util.SubnetUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
使用时如何选择?
InetAddress
类:简单易用,适合大多数场景,尤其是只需要获取本地主机的IP地址时。NetworkInterface
类:适合需要获取所有网络接口的IP地址,或者需要过滤特定类型的IP地址(如非回环地址、本地地址等)的场景。总结
对于大多数简单场景,使用 InetAddress.getLocalHost()
是最简单和直接的方式。如果你需要更细粒度的控制或处理多个网络接口,可以使用 NetworkInterface
类。
作者:五道书童