简体   繁体   中英

Set static ip if not obtained from DHCP (script)

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 

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

Although an old question, it might be worth noting here that Gentoo Linux has had this functionality for a long time (I've been using it since 2004). Gentoo's network config file (/etc/conf.d/net) allows for fallback IP addresses to be easily specified for any interface in the event that DHCP fails, eg:

modules="dhclient"
config_eth0="dhcp"
config_eth1="dhcp"
dhclient_eth1="nogateway"
fallback_eth0="apipa"
fallback_eth1="192.168.10.10/24"
fallback_routes_eth1="default via 192.168.10.1"

The solution Maurizio provided to use an alias like eth0:0 is fine in many (probably most) situations, but not all. I've run into one piece of software that does not consider eth0:0 to be a suitable substitute for eth0 when it is undefined due to no answer from DHCP, even though it is the same port. So a static fallback address is slightly superior to the alias solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM