How to configure an IP in a Linux network interface?

Configure a dynamic IP with DHCP

When we configure a host with a dynamic IP, the router is responsible for assigning a (variable) IP address to the connected network card.

RedHat / Fedora / CentOS

$ sudo cat /etc/sysconfig/network-scripts/ifcfg-eth0
HWADDR=88:AE:1D:69:5A:5A
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=eth0
UUID=2efbd6c0-e3d5-45af-9631-10635fd6a39a
ONBOOT=yes

Debian / Linux Mint

$ sudo cat /etc/network/interfaces
iface eth0 inet dhcp

Ubuntu

Ubuntu uses the network management tool called Netplan. Its configuration file is located in the /etc/netplan directory. If we want to find out the name of the configuration file on our system, we just need to run an ls command.

$ ls /etc/netplan
Now we can access the configuration file shown by the previous command
sudo nano /etc/netplan/01-network-manager-all.yaml

Example using DHCP:

network: version: 2 ethernets: eth0: dhcp4: yes

Configure a static IP

If, on the other hand, we want to manually assign an IP address to each host/device in the network, we can configure the interface to always retain/receive the same IP address.

RedHat / Fedora / CentOS

$ sudo cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO="static"
IPADDR="192.168.1.32"
NETMASK="255.255.255.0"
NETWORK="192.168.1.0"
BROADCAST="192.168.1.255"
GATEWAY="192.168.1.1"
ONBOOT="yes"

Note: In some systems, the interface name (eth0) may change to another name (e.g., enp1s0, wireless…).

Debian  / Linux Mint

$ sudo cat /etc/network/interfaces
iface eth0 inet static
address 192.168.1.23
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
hwaddress 81:ab:1c:59:aa:7b

Ubuntu

Access the configuration file with

sudo nano /etc/netplan/01-network-manager-all.yaml

After we can proceed to change the configuration of the network interface.

network: version: 2 ethernets: eth0: dhcp4: no addresses: - 192.168.1.100/24 gateway4: 192.168.1.1 nameservers: addresses: - 8.8.8.8 - 8.8.4.4

Note: In systems that use NetworkManager to manage the network, we may find the file /etc/NetworkManager/system-connections/<connection-name> storing the interface configuration:

[802-3-ethernet]
mac-address=88:AE:1D:69:5A:5A

[connection]
id=wired-11
uuid=212274c7-08bc-4586-9h49-c1u218p9239f
type=802-3-ethernet
timestamp=1424866869

[ipv6]
method=auto

[ipv4]
method=manual
dns=8.8.8.8;8.8.4.4;
address1=192.168.1.50/24,192.168.1.1

Note: The router usually assigns the DNS servers (since it has its own DNS configured). Otherwise, we can specify them in the file /etc/resolv.conf, defining a <host-name IP> per line (up to three lines).