Dibbler - a portable DHCPv6  1.0.2RC1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Using the client library

Exceptions

The Poslib library is built using 100% pure C++. One of the implications of this is, that Poslib uses exceptions all the way. This is a very important thing, because when a poslib function fails to do its job, it will throw an exception to notify you of its failure, instead of just returning an error value the C way. For this exception handling, Poslib uses its own exception class, PException, which has one member variable, PException::message, which will contain a description of the error. For example, you could call a Poslib function thus:

try {
domainname x = "www"; // this might throw an exception
x += "acdam.net"; // this might fail as well
} catch (PException p) {
printf("Error during domain name construction: %s\n", p.message);
}

Another issue is the usage of the STL. Poslib uses the STL on several occasions, including the nonstandard slist. Poslib refers to this STL objects as stl_slist, stl_list and stl_string. This is because for debug builds, we use the malloc_alloc allocator. These typedefs make life with STL much easier. So, when you use Poslib STL objects, be sure to refer to them using the stl_* typedefs.

Either way, enough about this, let's start writing some code! Here's a simple example, that will lookup an IP address for a given domain name:

#include <stdio.h>
#include <poslib/poslib.h>
int main(int argc, char **argv) {
_addr addr;
DnsMessage *q = NULL, *a = NULL;
try {
/* get command-line arguments */
if (argc == 3 && argv[1][0] == '@') {
txt_to_addr(&addr, argv[1] + 1);
q = create_query(argv[2]);
} else if (argc == 2) {
txt_to_addr(&addr, "127.0.0.1");
q = create_query(argv[1]);
} else {
printf("Usage: host [@if] host\n");
return 1;
}
res.query(q, a, &addr);
ip = get_a_record(a);
printf("%s has address %d.%d.%d.%d\n", q->questions.begin()->QNAME.tocstr(), ip.address[0], ip.address[1], ip.address[2], ip.address[3]);
} catch (PException p) {
printf("Fatal exception: %s\n", p.message);
return 1;
}
if (q) delete q;
if (a) delete a;
return 0;
}

This example uses the following Poslib functionality:

Also, note the use of the try...catch block with the PException object we used here. Any error that might occur will be caught by this block and reported to the user.

On my Linux box, I compiled this code using the following command (this should work on any Unix box, and possibly also under Mingw's MSys for Windows):

g++ `poslib-config --libs --cflags` host.cpp -o host 

You can read more information about the various pieces Poslib contains by viewing the source file and class documentation.