Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Practical Usage of Boost.ASN1

Lets say we want to build a simple protocol to transmit a phonebook. We are interested in the first and last name, plus a list of phone numbers and the type of phone the number represents.

The following represents a very simplistic phone contact PDU:

ASN1 Boost.ASN1
Phone ::= SEQUENCE {
  number OCTET STRING,
  type INTEGER
}

PhoneList SEQUENCE OF Phone

Contact := SEQUENCE {
  LastName OCTET STRING,
  FirstName OCTET STRING,
  PhoneLists PhoneList
  }
struct phone
{
  octetstring_t number;
  integer_t type;
};

typedef sequence<phone> phone_list;

struct contact
{
  octetstring_t LastName;
  octetstring_t FirstName;
  sequence_of<phone_list> phones;
};

Now, to populate this PDU with some useful data, we would do the following:

sequence<contact> Contact;

Contact.LastName = "Smith";
Contact.FirstName = "John";
Contact.phones[0].number = "7145551212"; // Home phone
Contact.phones[0].type = 1;         
Contact.phones[1].number = "2136664545"; // Mobile 1 phone
Contact.phones[1].type = 2;
Contact.phones[2].number = "3107777878"; // Mobile 2 phone
Contact.phones[2].type = 2;

Now, to package this up so asn_encode can do it's work, we do the following:

asn_base_ptr pduPtr;
Contact.to(pduPtr);

iostream ostrm;
asn_encode<ber_taglen> encoder(ostrm);
encoder.execute(pduPtr);

On the opposite side of the transmission, decoding and accessing the data is really simply.

Contact2.from(ContactRequest);
cout << Contact2.LastName << endl;
cout << Contact2.FirstName << endl;
for( size_t i = 0; i < Contact2.phones.size(); ++i )
{
  cout << "-----" << endl;
  cout << Contact2.phones[i].number << endl;
  cout << Contact2.phones[i].type << endl;
}

Copyright © 2007 Andreas Haberstroh

PrevUpHomeNext