Skip to content

Create your own element

Tom Barbette edited this page Nov 19, 2018 · 6 revisions

This tutorial will take you through the creation of your own Click element.

Click elements can be found in the elements folder. They are sorted by categories, which correspond more or less to the categories that can be found in the Elements page.

Own developments can take place in the folder elements/local/.

As any C++ classes elements are implemented through a source file (.cc) and a header file (.hh).

A minimal element would be composed of theses two files :

elements/local/myelement.cc

#include <click/config.h>
#include "myelement.hh"
CLICK_DECLS

Packet *
MyElement::simple_action(Packet *p) {
    click_chatter("Received a packet of size %d !", p->length());
}

CLICK_ENDDECLS
EXPORT_ELEMENT(MyElement)

elements/local/myelement.hh

#ifndef CLICK_MYELEMENT_HH
#define CLICK_MYELEMENT_HH
#include <click/batchelement.hh>
CLICK_DECLS

class MyElement : public SimpleElement<MyElement> { public:

    MyElement() CLICK_COLD {};

    const char *class_name() const              { return "MyElement"; }
    const char *port_count() const              { return PORTS_1_1; }

    Packet *simple_action(Packet *);
}

CLICK_ENDDECLS
#endif

Let's start with the hh file. The definition of the class MyElement is pretty standard, excepts it inherits a special SimpleElement template that will automatically make the element batch-compatible, and hence very efficient. Old vanilla Click elements would simply inherit Element, while if you want to write different packet and batch processing function you may extend BatchElement.

The class_name() defines the element name, usually identical to the class. And port_count defines the number of I/O ports. See the Element class documentation for more informations about those.

The simple_action function will be called for every packets passing by. The .hh file only contains the declaration, the core of the code is in the .cc file.

Clone this wiki locally