User Tools

Site Tools


wsn:ns2:packet

Adding new packet types to NS-2

Learn how to add new packet types to NS-2. All NS-2 packet types are handled as if they are simple byte arrays. Therefor NEVER use object-oriented stuff like polymorphism or class constructors when working with NS-2 packets. At startup all registrated NS-2 packet types are merged together. Carrier of this big packet structure are instances of class Packet .

All code fragments are part of simple_ns2_example.zip. Now 4 steps have to be taken to add new packet types.

1.) Writing the code

from file MyPacket.h

#include "packet.h"

struct hdr_myHeader {
	// your data fields
	int myData;
	int &getMyData() { return myData; }

	// necessary for access
	static int offset_;
	inline static int& offset() { return offset_; }
	inline static hdr_myHeader* access(const Packet* p) {
		return (hdr_myHeader*) p->access(offset_);
	}
};

The field offset_ points to the position in the NS-2 byte array (merged packet), where the header is stored.

2.) Static binding of packet

from file MyPacket.cc

static class MyHeaderClass : public PacketHeaderClass {
public:
	MyHeaderClass() : PacketHeaderClass("PacketHeader/MyHeader",sizeof(hdr_myHeader)) {
		bind_offset(&hdr_myHeader::offset_);
	}
} classMyHeader;

int hdr_myHeader::offset_;

By using a static derivative object of class PacketHeaderClass, the name, size and offset of packet structure will be registrated at startup. Here you see that NS-2 get only the size of the packet to know. For this reason the programm handles packets like byte arrays and the use of class (de)constructors should be avoided.

3.) Modifying packet.h

You will find this file in the common directory of NS-2.

Add following lines to enumeration:

enum packet_t {
        ...
        // insert new packet types here
	PT_MYHEADER,  //<-- add this line
	
	// This MUST be the LAST one
	PT_NTYPE 

All known packet headers are saved in this big enumeration. A second change in this file has to be made in class p_info :

class p_info {
public:
	p_info() {
        ...
	// insert new packet types here
	 name_[PT_MYHEADER] = "MyHeader";//<-- add this line
		
        // last
        name_[PT_NTYPE]= "undefined";

4.) Compiling

Be careful by calling make. Changes of packet.h are not recompiled, because packet.cc stays unmodified. A simple solution is to resave packet.cc. (Of course you can call make clean and after that make, but this is time-consuming.)

After receiving a NS-2 packet, you can access your new type by using this code:

    hdr_myHeader *p_myHeader = hdr_myHeader::access(p);
wsn/ns2/packet.txt · Last modified: 2012/11/08 14:14 (external edit)