Skip to main content

ArtinTech Solution

Routeros online sessions in Linkhive

Most PHP projects that talk to MikroTik pull in a package. For Linkhive, our ISP billing platform, we wrote a small RouterOS API PHP client instead, because the protocol is simple and every router call affects a customer’s service.

Words and sentences

The API runs over TCP on port 8728, or TLS on 8729. A command is a sentence made of words, and each word is sent with its length in front. The router answers with sentences that start with !re for a row, !trap for an error, !fatal when it drops the connection, and !done when it has finished.

Two ways to log in

Since RouterOS 6.43 the login sends the name and password directly. Older versions answer with a challenge, so the client handles both:

$done = $this->talk(['/login', '=name='.$username, '=password='.$password])['done'];

if (isset($done['ret'])) {
    $response = '00'.md5(chr(0).$password.hex2bin($done['ret']));
    $this->talk(['/login', '=name='.$username, '=response='.$response]);
}
Linkhive Online now page listing sessions with customer, package, IP, MAC address, uptime, router and traffic
Sessions read from /ppp/active and /ip/hotspot/active on each router.

Keep the driver idempotent

On top of the client sits a driver with one upsert helper: look up the record by name, update it if it exists, add it if not. Running the same change twice therefore does no harm, which matters because failed changes are retried. A !trap becomes an exception, and the provisioning layer catches it, logs it and flags the subscription for a retry.

Key takeaways

  • The RouterOS API is simple enough to implement in about two hundred lines.
  • Support both login methods if your customers run older routers.
  • Make every router write an upsert, so that retries are safe.

Note that our client does not verify the router’s TLS certificate, because routers usually carry self-signed ones. Treat TLS as encryption on a network you control.

See it in the Linkhive live demo or get Linkhive on Vibe96. Need a custom MikroTik integration? Let’s Talk, or see our Laravel development service.

Share this article