Putting payload in a Packet

If you don’t care about the actual content of the payload, the following will keep track of 1024 bytes of payload filled with zeros

uint32_t size = 1024;
Ptr<Packet> p = Create<Packet> (size);

Putting real bytes in the payload

If you do care about the actual content of the packet payload, you can also request the packet to copy the data in an internal buffer:

uint8_t *buffer = ...;
uint32_t size = ...;
Ptr<Packet> p = Create<Packet> (buffer, size);

Adding data to an existing packet

If you have an existing packet and you need to add data at its start or its end, you need to create a new Header (Trailer). First, subclass the Header(Trailer) class:

class MyHeader : public Header
{
public:
  // new methods
  void SetData (uint16_t data);
  uint16_t GetData (void);
  // new method needed
  static TypeId GetTypeId (void);
  // overridden from Header
  virtual uint32_t GetSerializedSize (void) const;
  virtual void Serialize (Buffer::Iterator start) const;
  virtual uint32_t Deserialize (Buffer::Iterator start);
  virtual void Print (std::ostream &os) const;
private:
  uint16_t m_data;
};

Typical implementations of the SetData/GetData methods will look like this:

void 
MyHeader::SetData (uint16_t data)
{
  m_data = data;
}
uint16_t
MyHeader::GetData (void)
{
  return m_data;
}

While the overridden methods would look like this:

uint32_t 
MyHeader::GetSerializedSize (void) const
{
  // two bytes of data to store
  return 2;
}
void 
MyHeader::Serialize (Buffer::Iterator start) const
{
  start.WriteHtonU16 (m_data);
}
uint32_t 
MyHeader::Deserialize (Buffer::Iterator start)
{
  m_data = start.ReadNtohU16 ();
  return 2;
}
void 
MyHeader::Print (std::ostream &os) const
{
  os << m_data;
}

And, finally, you need to implement GetTypeId:

TypeId
MyHeader::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::MyHeader")
    .SetParent<Header> ()
    ;
  return tid;
}

And, now, you can use this new header to store data in the packet as follows:

Ptr<Packet> p = ...;
MyHeader header = ...;
header.SetData (10);
p->AddHeader (header);

or remove data from the packet:

Ptr<Packet> p = ...;
MyHeader header;
p->RemoveHeader (header);
header.GetData ();