Set static ip if not obtained from DHCP (script)
Asked Answered
H

2

12

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 
Hamitic answered 4/10, 2012 at 12:21 Comment(0)
L
27

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
Lutanist answered 4/10, 2012 at 13:28 Comment(4)
I use udhcpc and made something like: udhcpc -n -f -i eth0 if ifconfig | grep -A1 eth0 | grep inet thenHamitic
Why not also auto eth0?Ot
@Ot why not auto <if> causes the interface to be brought up automatically during boot, not manually by something like ifup. Consult the manual for details.Tweedsmuir
On linux4tegra I needed to add auto eth0 in order for it to ry dhcp when bootingCoeval
D
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, e.g.:

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.

Darcie answered 26/1, 2020 at 3:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.