• Print
  • Share
  • Dark

Formatting MAC addresses in dhcpd (or 'why does binary-to-ascii strip leading zeroes?')

  • Updated on 25 Oct 2018
  • 1 minute to read
  • Contributors

This question arises from time to time when an administrator uses binary-to-ascii in dhcpd.conf, hoping to obtain the hardware address of a device that has been assigned a lease. The problem is that where a component of the address has a leading zero, this zero will be omitted in the output.

Here's a typical example of usage that doesn't work quite as expected:

set foo = binary-to-ascii(16, 8, ":", substring(hardware, 1, 6));

Instead of the expected hardware address format - for example f8:0c:f3:**:**:**, foo will instead contain f8:c:f3:**:**:**.

This is not a bug. The problem is that the binary-to-ascii function doesn't "know" anything about the intended use of the converted binary digits and it's unusual to include leading zeroes when printing numeric values.

However, with a bit of additional manipulation it's still possible to get the desired result:

set foo = concat (
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,1,1))),2), ":",
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,2,1))),2), ":",
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,3,1))),2), ":",
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,4,1))),2), ":",
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,5,1))),2), ":",
suffix (concat ("0", binary-to-ascii (16, 8, "", substring(hardware,6,1))),2)

(It operates by converting each "component" separately, adding a leading zero to it (in case one is needed); taking the last two hex characters, and then concatenating them all together again.)

Was this article helpful?