Category Archives: Mikrotik

Mikrotik DHCP to DNS hostnames

When I previously worked with DNSMASQ such thing was handled automatically. DHCP client sends his hostname and DHCP server then server add’s this hostname to DNS allowing clients to access host by hostname. There were some issues with static names but this is different story. In common it worked good. It was a surprise for me that Mikrotik doesn’t support such feature out of box.

After some time of reading wiki and googling I’ve came with my own solution.

My script is using ttl and domain name to distinguish between static and dynamic clients.

:local zone "localdomain"
:local timetolive "00:05:00"
:local hostname
:local ip
:local dnsip
:local dhcpip
:local dnsnode
:local dhcpnode

/ip dns static;
:foreach i in=[find where name ~ (".*\\.".$zone) and ttl ~ $timetolive] do={
  :set hostname [ get $i name ];
  :set hostname [ :pick $hostname 0 ( [ :len $hostname ] - ( [ :len $zone ] + 1 ) ) ];
  /ip dhcp-server lease;
  :set dhcpnode [ find where host-name=$hostname ];
  :if ( [ :len $dhcpnode ] > 0) do={
    :log debug ("Lease for ".$hostname." still exists. Not deleting.");
  } else={
    :log info ("Lease expired for ".$hostname.", deleting DNS entry.");
    /ip dns static remove $i;
  }
}

/ip dhcp-server lease;
:foreach i in=[find] do={
  :set hostname ""
  :local mac
  :set dhcpip [ get $i address ];
  :set mac [ get $i mac-address ];
  :if ( [ :len $hostname ] = 0) do={
    :set hostname [ get $i host-name ];
  }
  :if ( [ :len $hostname ] > 0) do={
    :set hostname ( $hostname . "." . $zone );
    /ip dns static;
    :set dnsnode [ find where name=$hostname ];
    :if ( [ :len $dnsnode ] > 0 ) do={
# it exists. Is its IP the same
      :set dnsip [ get $dnsnode address ];
      :if ( $dnsip = $dhcpip ) do={
        :log debug ("DNS entry for " . $hostname . " does not need updating.");
      } else={
        :log info ("Replacing DNS entry for " . $hostname);
        /ip dns static remove $dnsnode;
        /ip dns static add name=$hostname address=$dhcpip ttl=$timetolive;
      }
    } else={
# it doesnt exist. Add it
      :log info ("Adding new DNS entry for " . $hostname);
      /ip dns static add name=$hostname address=$dhcpip ttl=$timetolive;
    }
  }
}

One needs to put this script to Mikrotik router and schedule execution each 5 minutes.

/system scheduler
add interval=5m name=dhcp-dns-run on-event=dhcp-dns start-time=00:00:00

Another thing that needs to be mentioned it that DHCP server on your Mikrotik needs to provide clients with domain name. Something like this:

/ip dhcp-server network
add address=192.168.88.0/24 comment="default configuration" dns-server=192.168.88.254 domain=localdomain gateway=192.168.88.254 netmask=24

I hope I didn’t miss anything important. 😉