librouteros

From MikroTik Wiki
Jump to: navigation, search

librouteros is a free and open-source library written in C which abstracts the API provided by RouterOS. It was initially written in 2009 by Florian Forster and released under the GNU General Public License (GPL).

Features and design goals are:

  • Ease of use: The library makes heavy use of callback functions which simplifies memory management.
  • Strict ISO C99 and POSIX.1-2001 conformance.
  • Thread and reentrant-safety.
  • Abstraction from underlying network protocol.
  • Well documented using manual pages.

Compiling

librouteros uses the autotools and libtool and can therefore be compiled and installed with the usual set of commands:

~ $ tar jxf librouteros-x.y.z.tar.bz2
~ $ cd  librouteros-x.y.z
librouteros-x.y.z $ ./configure
librouteros-x.y.z $ make
librouteros-x.y.z $ make install

Dependencies

librouteros uses the gcrypt library from the GnuPG project to calculate the MD5-hash required for authenticating.

Example program

The following (untested!) example program demonstrates how to get a list of interfaces from a device running RouterOS and print this list to standard output. It is using the high-level function ros_interface which provides a list of interfaces on the router. For a more thorough example please tend to the ros command line utility which is included with the librouteros source code distribution. It demonstrates how to handle generic queries and registration-table entries, too.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include "routeros_api.h"

/* Print the list of interfaces. */
static void print_interface (const ros_interface_t *if)
{
  if (if == NULL)
    return;
  
  printf ("%s (%s, %s, %s, %s)\n", if->name, if->type,
      if->dynamic ? "dynamic" : "static",
      if->running ? "running" : "stopped",
      if->enabled ? "enabled" : "disabled");
  
  print_interface (if->next);
}

/* Callback function that is called by "ros_interface" */
static int handle_interfaces (ros_connection_t *c, const ros_interface_t *if, void *user_data)
{
  print_interface (if);
  return (0);
}

int main (int argc, char **argv)
{
  ros_connection_t *c;
  
  /* Connect to the router */
  c = ros_connect ("my-router.example.com", ROUTEROS_API_PORT,
      "api_user", "secret");
  if (c == NULL)
  {
    fprintf (stderr, "ros_connect failed: %s\n", strerror (errno));
    exit (EXIT_FAILURE);
  }
  
  /* Query a list of interfaces and call "handle_interfaces". */
  ros_interface (c, handle_interfaces, /* user data = */ NULL);
  
  /* Disconnect from the router. */
  ros_disconnect (c);
  exit (EXIT_SUCCESS);
}

External links