Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 749
Bartlomiej Grzeskowiak Avatar asked Oct 04 '12 12:10

Bartlomiej Grzeskowiak


People also ask

Do I need a DHCP reservation for a static IP?

You'll need DHCP IP reservation (Static IP for your client) if you want to set up port forwarding to that device. You can customize the subnet you use under LAN settings (if you prefer to use a different subnet).

How do I set a static IP in DHCP?

To do this, go to Config > Network > DHCP Server. On the left side of the screen is a box labelled "Static DHCP Entries". Click Add and enter the device's MAC address and the intended IP address. On the right side of the screen are the current DHCP assigned IP addresses.

Does DHCP override static IP?

In short the general rule of thumb is no the DHCP server will not know about this Static IP and if hands that same IP out to another device you will have an IP conflict which can take both devices offline.


1 Answers

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
like image 165
Maurizio Lo Bosco Avatar answered Sep 28 '22 16:09

Maurizio Lo Bosco