如果没有从DHCP获取静态IP(脚本)

Bar*_*iak 10 linux ip dhcp ifconfig

我在linux上使用嵌入式设备.我想先使用DHCP客户端,但如果DHCP服务器没有应答,我想设置静态默认IP.我想这应该不复杂,但我没有找到严格的答案.

我正在考虑2个解决方案(不幸的是我可以在几天内测试它们):

  1. 我用ifconfig设置静态IP,然后我调用udhcpc.如果udhcpc无法获得新的IP,旧的IP将保留.

  2. 我也可以先调用udhcpc,稍等片刻,检查是否获得了IP.但这对我来说并不好.我不想在启动时添加任何等待例程.

BR Bartek

我使用udhcpc - 类似于:

udhcpc -n -f -i eth0 
if ifconfig | grep -A1 eth0 | grep inet 
    then 
Run Code Online (Sandbox Code Playgroud)

Mau*_*sco 23

dhclient应该支持通过租约声明回退看一下dhclient.conf手册页.

添加这样的东西到你的 dhclient.conf

timeout 10;
lease {
interface "eth0";
fixed-address 10.0.0.10;
option subnet-mask 255.255.255.0;
renew 2 2022/1/1 00:00:01;
rebind 2 2022/1/1 00:00:01;
expire 2 2022/1/1 0:00:01;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以为界面分配第二个IP /etc/network/interfaces

auto lo
iface lo inet loopback
iface eth0 inet dhcp

auto eth0:1
iface eth0:1 inet static
address 10.10.10.2
netmask 255.255.255.0
Run Code Online (Sandbox Code Playgroud)

  • 我使用 udhcpc 并做了类似的事情: udhcpc -n -f -i eth0 if ifconfig | grep -A1 eth0 | grep -A1 eth0 | grep -A1 eth0 | 然后 grep inet (2认同)