Java在Linux进行网络配置主要有以下两种方式:
通过修改配置文件(永久生效)
/etc/netplan/目录下的.yaml文件(如01-netcfg.yaml),配置IP地址、网关、DNS等参数,保存后执行sudo netplan apply。/etc/sysconfig/network-scripts/ifcfg-<接口名>文件,设置BOOTPROTO=static,并配置IPADDR、NETMASK、GATEWAY等,保存后执行sudo systemctl restart network。通过Java代码调用系统命令(临时生效)
使用Runtime.getRuntime().exec()执行Linux命令,如ip addr add、ip route add等。需注意:
sudo。// 示例:添加静态IP(需根据实际接口名修改)
String cmd = "sudo ip addr add 192.168.1.100/24 dev eth0 && sudo ip link set eth0 up";
try {
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
验证配置:
ip addr show或ifconfig查看IP是否生效。ping测试网络连通性,nslookup测试DNS解析。注意事项: