The full source code can be found in examples/ldns-read-zone.c
ldns-read-zone reads a zone file, and prints it to stdout, with 1 resource record per line.
% cat example.zone $ORIGIN example. $TTL 600
example. IN SOA example. op.example. ( 2004022501 ; serial 28800 ; refresh (8 hours) 7200 ; retry (2 hours) 604800 ; expire (1 week) 18000 ; minimum (5 hours) )
@ IN MX 10 mail.example. @ IN NS ns1 @ IN NS ns2 @ IN A 126.96.36.199
% ldns-read-zone example.zone example. 600 IN SOA example. op.example. 2004022501 28800 7200 604800 18000 example. 600 IN MX 10 mail.example. example. 600 IN NS ns1.example. example. 600 IN NS ns2.example. example. 600 IN A 188.8.131.52
Again, let's start with including some necessary header files:
In this example, we are going to open a file, if that fails, we'll need errno.h to display an error message.
Okay, let's declare the variables we are going to need today:
The only two ldns-specific types here are
ldns_zoneis the structure that can contain a complete zone
ldns_statusagain is used to check return values of ldns functions
If we get no filename, we'll read standard input, otherwise, we'll try to open the given filename:
FILE pointer in our hands, we visit ldns to pour it into a zone structure:
There is also a
ldns_zone_new_frm_fp, but this one also remembers the line number it was on, so we can use that if we encounter a parse error.
Just like in Tutorial 1: Querying for MX records, the first argument is a pointer to the place ldns should store its creation in, and again, the return value is the status code.
The second argument is the file pointer where our zone data should reside.
The third argument, if not NULL, is a
dname that contains the zones origin. It will place this dname after every name in the file that is not a fully qualified domain name.
The fourth argument, if not 0, is the default TTL to use.
Both these values can be specified in the zone file by setting
The fifth argument specifies the default class, which defaults to IN (LDNS_RR_CLASS_IN).
And finally, every time
ldns_zone_new_frm_fp_l reads a line from the input file pointer, it will increment the value pointed to by the last argument with 1.
Okay, with that, we should have a nice zone structure. Of course we need to check whether it has succeeded.
If everything went well, we sort the zone if necessary, print it, and free it.
ldns_zone contains other ldns structures, we use
ldns_deep_free so that every
ldns_rr et cetera are freed too.
If something went wrong, we use
ldns_get_errorstr_by_id() to get a nice error string instead of just a status integer.
And of course, we should play nice and close the file: