Set static ip if not obtained from DHCP (script)

2019-02-07 00:37发布

I work on embedded device with linux on it. I want to use DHCP client first, but if there will be no answer from DHCP Server I want to set static-default IP. I suppose it shouldn't be complicated, but I haven't found strict answer.

I'm thinking about 2 solutions (Unfortunately I can test them in few days):

  1. I set static IP with ifconfig, then I call udhcpc. If udhcpc will not obtain new IP, old one will stay.

  2. I can also first call udhcpc, wait a while and check if IP is obtained. But this is not nice for me. I wouldn't like to add any wait routines into startup.

BR Bartek

I use udhcpc - something like:

udhcpc -n -f -i eth0 
if ifconfig | grep -A1 eth0 | grep inet 
    then 

1条回答
太酷不给撩
2楼-- · 2019-02-07 01:19

dhclient should support fallback via lease declaration have a look at the dhclient.conf man page.

Add something like this to your 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;
}

or you can assign a second IP to the interface like /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
查看更多
登录 后发表回答