Commit 6daaba2c authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Add Network.get_free_address

parent f994bd31
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
@@ -403,6 +403,27 @@ class Network(Item):
		"""
		docker_quiet("network", "rm", self._name)

	def get_free_address(self) -> ipaddress.IPv4Address:
		"""
		Return a free address in the network

		Note that the address is not reserved; any changes made to the network such as
		adding a container may invalidate the assurance that the address is free.
		"""
		# TODO: support IPv6
		data = self.inspect()
		# Considering only the first listed subnet
		net = data.path("$.IPAM.Config[0].Subnet", str, ipaddress.IPv4Network)
		reserved = data.path(
			"$.Containers.*.IPv4Address", list[str],
			lambda addrs: {IPv4Address.with_suffix(a) for a in addrs},
		)
		reserved.add(data.path("$.IPAM.Config[0].Gateway", str, IPv4Address))
		for addr in net.hosts():
			if addr not in reserved:
				return addr
		raise LookupError(f"No free addresses found in subnet {net}")


class Cli:
	"""