Java 获取本机IP地址的方法的两种方法
在 Java 编程中,若有本机的 IP 地址的需求,小编来展示一下方法:
一、使用 InetAddress.getLocalHost
一是最基本的获取本机 IP 地址的方式。
示例代码:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIPAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("本机 IP 地址: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
这种方法在大多数简单场景下可以正常工作,但如果主机有多个网络接口或者处于复杂的网络环境中,可能获取到的不是期望的 IP 地址。
二、遍历网络接口获取
通过遍历所有网络接口来获取更准确的 IP 地址信息。
示例代码:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetIPAddressByInterface {
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.getHostAddress().indexOf(':') == -1) {
System.out.println("本机 IP 地址: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
上述代码首先获取所有网络接口,然后遍历每个接口下的 IP 地址,排除回环地址(isLoopbackAddress 判断)和 IPv6 地址(通过 indexOf(‘:’) == -1 判断),从而得到可能的本机 IP 地址。这种方法在复杂网络环境中能获取到多个符合条件的 IP 地址,可根据实际需求进一步筛选。
通过以上两种方法,可以在 Java 程序中获取本机的 IP 地址,开发人员可根据具体的应用场景选择合适的方法使用。
到此这篇关于Java 获取本机IP地址的方法的两种方法的文章就介绍到这了,更多相关Java 获取本机IP地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot pdf打印及预览(openhtmltopdf+freemarker)
这篇文章主要介绍了SpringBoot pdf打印及预览(openhtmltopdf+freemarker)2023-05-05
spring boot 使用Aop通知打印控制器请求报文和返回报文问题
这篇文章主要介绍了spring-boot 使用Aop通知打印控制器请求报文和返回报文,非常不错,具有参考借鉴价值,需要的朋友可以参考下2018-04-04
MyBatis-Plus更新对象时将字段值更新为null的四种常见方法
MyBatis-Plus 是一个 MyBatis 的增强工具,在简化开发、提高效率方面表现非常出色,而,在使用 MyBatis-Plus 更新对象时,默认情况下是不会将字段值更新为 null 的,如果你需要将某些字段的值更新为 null,有几种方法可以实现,本文将介绍几种常见的方法2024-11-11


最新评论