19

I'm trying to find a genric solution across all linux distro to find if the IP address attached to the system is a static or a DHCP ?

On ubuntu , I can find if it's static or DHCP by doing a DHCP grep on /var/log/syslog but it is not generic solution , it might differ on other platforms.

One of the target board is Cortina and I'm using open wrt as a boot up kernel for that. There is no var/log/syslog on Cortina nothing similar to that also.

Giacomo1968
  • 58,727
Neetz
  • 305

6 Answers6

14
ip a | grep dynamic

If output is nothing -> your IP address is statically assigned.

If output is a line with dynamic in it -> your IP address is dynamically/dhcp assigned.

If the IP address is assigned by dhcp your line should be something like this:

inet 192.168.1.5/24 brd 192.168.1.255 scope global dynamic noprefixroute enp0s3

Tested on Debian and Rocky Linux (CentOS)...

Damir
  • 281
5

If its CentOS, you can check /etc/sysconfig/network-scripts/ifcfg-eth0. Check BOOTPROTO entry says. If its dhcp then its DHCP configured. If its Static or none, then its not DHCP

5

You have the command in nmcli.
This should work in all Linux flavors, I believe:

nmcli -f ipv4.method con show eno16780032

If the output is auto, then it is DHCP.
If the output is manual, then it is static.

zx485
  • 2,337
Satish Sura
  • 75
  • 1
  • 1
4

The problem is, if you're using NetworkManager, for example, it's going to be requesting an IP and gateway and DNS server. But beyond that, once it's got the information it needs, it sets addressing information essentially statically. Essentially, the rest of your machine doesn't know or care if an address is static or dynamic, just that it has an address.

You can check /var/log/syslog for DHCPACK entries specifically. I believe dhclient and NetworkManager write there.

hlmtre
  • 61
3

Type in terminal

cat /etc/network/interfaces

You should find one of this lines

iface eth0 inet dhcp

that means that IP for interface eth0 is from DHCP

iface eth0 inet static

Above line shows that IP is static. You should also find other parameters.

1

In my testing in 2023, this works in multiple versions of CentOS/Rocky/RedHat/SuSE and Ubuntu:

# These are inverse of each other:
ip route list default | grep dhcp
ip route list default | grep static

Note: ip command is provided by iproute or iproute2 package, depending on the distribution.

Static IP command output:

$ ip route list default
default via X.X.X.X dev ens160 proto static metric 100 

DHCP command output:

$ ip route list default
default via X.X.X.X dev ens192 proto dhcp src Y.Y.Y.Y metric 100

Bash Example

if ip route list default | grep dhcp > /dev/null ; then 
   Do Something on DHCP machines
fi

credit

Extra credit: Puppet Integration

Puppet fact example:

Facter.add("is_dhcp") do
  setcode do
    route = Puppet::Util::Execution.execute(['ip route list default'], :failonfail => false)
    result = route ? "#{route}".match?(/dhcp/) : false
  end
end
akom
  • 255