diff --git a/nixos/modules/services/networking/dhcpcd.nix b/nixos/modules/services/networking/dhcpcd.nix index cdba14be21f0..d283c7624335 100644 --- a/nixos/modules/services/networking/dhcpcd.nix +++ b/nixos/modules/services/networking/dhcpcd.nix @@ -153,10 +153,14 @@ in config = mkIf enableDHCP { - systemd.services.dhcpcd = + systemd.services.dhcpcd = let + cfgN = config.networking; + hasDefaultGatewaySet = (cfgN.defaultGateway != null && cfgN.defaultGateway.address != "") + || (cfgN.defaultGateway6 != null && cfgN.defaultGateway6.address != ""); + in { description = "DHCP Client"; - wantedBy = [ "network-online.target" ]; + wantedBy = optional (!hasDefaultGatewaySet) "network-online.target"; after = [ "network.target" ]; wants = [ "network.target" ]; diff --git a/nixos/modules/tasks/network-interfaces-scripted.nix b/nixos/modules/tasks/network-interfaces-scripted.nix index 15b36cfcb113..7ede8752bcc3 100644 --- a/nixos/modules/tasks/network-interfaces-scripted.nix +++ b/nixos/modules/tasks/network-interfaces-scripted.nix @@ -73,6 +73,9 @@ let then [ "${dev}-netdev.service" ] else optional (dev != null && dev != "lo" && !config.boot.isContainer) (subsystemDevice dev); + hasDefaultGatewaySet = (cfg.defaultGateway != null && cfg.defaultGateway.address != "") + || (cfg.defaultGateway6 != null && cfg.defaultGateway6.address != ""); + networkLocalCommands = { after = [ "network-setup.service" ]; bindsTo = [ "network-setup.service" ]; @@ -85,7 +88,7 @@ let before = [ "network.target" "shutdown.target" ]; wants = [ "network.target" ]; conflicts = [ "shutdown.target" ]; - wantedBy = [ "multi-user.target" ]; + wantedBy = [ "multi-user.target" ] ++ optional hasDefaultGatewaySet "network-online.target"; unitConfig.ConditionCapability = "CAP_NET_ADMIN"; diff --git a/nixos/tests/networking.nix b/nixos/tests/networking.nix index 6a7e628d8ef1..7708775f73f3 100644 --- a/nixos/tests/networking.nix +++ b/nixos/tests/networking.nix @@ -105,7 +105,7 @@ let startAll; $client->waitForUnit("network.target"); - $router->waitForUnit("network.target"); + $router->waitForUnit("network-online.target"); # Make sure dhcpcd is not started $client->fail("systemctl status dhcpcd.service"); @@ -157,7 +157,7 @@ let startAll; $client->waitForUnit("network.target"); - $router->waitForUnit("network.target"); + $router->waitForUnit("network-online.target"); # Wait until we have an ip address on each interface $client->waitUntilSucceeds("ip addr show dev eth1 | grep -q '192.168.1'");