def add_dhcp_server(api, network, interface="bridge", from_addr=100, to_addr=200):
"""
Add a DHCP server to the given interface and network.
:param api: The RouterOS API object.
:param interface: The interface to add the DHCP server to.
:param network: The network address to assign to the DHCP server (e.g., '
"""
# Compute range from network and from/to addresses
network_obj = ipaddress.ip_network(network, strict=False)
network_address = str(network_obj.network_address)
network_prefix = network_obj.prefixlen
network_split = network_address.split('.')
network_split[-1] = '0'
network_base = '.'.join(network_split)
from_address = '.'.join(network_split[:-1] + [str(from_addr)])
to_address = '.'.join(network_split[:-1] + [str(to_addr)])
range_str = f"{from_address}-{to_address}"
# First, add a pool of addresses for the DHCP server
print(f"Adding DHCP server pool for network {network}")
try:
api.get_resource('/ip/pool').add(name=f'dhcp_pool_{interface}', ranges=range_str)
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
if "pool with such name exists" in str(e):
print("DHCP pool already exists")
else:
raise e
# Now add a DHCP server for said pool
print(f"Adding DHCP server for network {network}")
try:
api.get_resource('/ip/dhcp-server').add(
interface=interface,
address_pool=f'dhcp_pool_{interface}',
lease_time='30m',
name=f'dhcp_server_{interface}',
disabled='no'
)
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
if "server with such name already exists" in str(e):
print("DHCP server already exists")
else:
raise e