To switch to DHCP you have to disable the IP Static connection profile and enable the DHCP connection profile.
This switching is executed by the use of the nmcli command.
A connection profile is saved in a file called <connection-name>.nmconnection
in the folder /etc/NetworkManager/system-connections
of the Ubuntu distribution.
In the rest of the answer I'll use the term connection to mean the term connection profile.
A way to pass from Static Ip to DHCP (and viceversa) by nmcli command is to create 2 NetworkManager connections one for Static Ip and one for DHCP. Both the first connection and the second manage the same ethernet interface.
For example I suppose that the name of 2 connections are:
ethernet_ipstatic
ethernet_dhcp
This means that, in the system in the path /etc/NetworkManager/system-connections
, there will be present 2 files called:
ethernet_ipstatic.nmconnection
ethernet_dhcp.nmconnection
The nmcli command for the creation of the 2 connections are:
# for ethernet_ipstaticnmcli c add ifname enp2s0 type ethernet con-name ethernet_ipstatic# for ethernet_dhcpnmcli c add ifname enp2s0 type ethernet con-name ethernet_dhcp
In the nmcli example commands the ethernet interface name is enp2s0
.
Now it is necessary to set properties of the 2 connections.
For the ethernet_ipstatic
the properties are:
nmcli con mod ethernet_ipstatic ipv4.method manual ipv4.addresses 192.168.1.1/24 ipv4.gateway 192.168.1.100 ipv4.may-fail no ipv6.method disabled connection.autoconnect no connection.autoconnect-priority -1
Previous command set the following properties for the connection:
For the ethernet_dhcp
the properties are:
nmcli con mod ethernet_dhcp ipv4.method auto ipv4.addresses '' ipv4.gateway '' ipv4.may-fail no ipv4.dhcp-timeout 20 ipv6.method disabled connection.autoconnect no connection.autoconnect-priority -1 connection.autoconnect-retries 3
Previous command set the following properties for the connection:
To set DHCP we can use the following sequence of nmcli commands:
# disable IP STATIC connectionnmcli con mod ethernet_ipstatic connection.autoconnect no connection.autoconnect-priority -1# enable DHCP connectionnmcli con mod ethernet_dhcp connection.autoconnect yes connection.autoconnect-priority 10# down IP STATIC connectionnmcli con down ethernet_ipstatic# up DHCP connectionnmcli con up ethernet_dhcp
To set Ip Static we can use the following sequence of nmcli commands:
# disable DHCP connectionnmcli con mod ethernet_dhcp connection.autoconnect no connection.autoconnect-priority -1# enable IP STATIC connectionnmcli con mod ethernet_ipstatic connection.autoconnect yes connection.autoconnect-priority 10# down DHCP connectionnmcli con down ethernet_dhcp# up IP STATIC connectionnmcli con up ethernet_ipstatic
The key for the correct operation of this method is to change the priority property of connection profiles when it is necessary to pass from IP Static to DHCP or viceversa.