在Java中获取Linux系统的IP地址,通常涉及到网络编程和系统命令的执行。Java提供了多种方式来获取本地IP地址,包括使用InetAddress
类和执行系统命令。
InetAddress
类:这是Java标准库中提供的方法,可以直接获取本地IP地址。ifconfig
或ip addr
。InetAddress
类import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetLocalIP {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("Local IP Address: " + inetAddress.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GetLocalIPByCommand {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ip addr show eth0");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("inet ")) {
System.out.println(line.split("/")[0].trim());
break;
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
InetAddress.getLocalHost()
返回错误的IP地址:/etc/hosts
文件和DNS配置。eth0
)。通过以上方法和示例代码,你可以轻松地在Java中获取Linux系统的IP地址,并解决可能遇到的问题。
云+社区沙龙online第5期[架构演进]
腾讯技术创作特训营
云+社区技术沙龙[第21期]
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
2022OpenCloudOS社区开放日
云+社区技术沙龙 [第30期]
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
Elastic 中国开发者大会
领取专属 10元无门槛券
手把手带您无忧上云