Altering DNS A-Records in the Compact Framework

Every time we release a new version of the SDF, even minor releases, we often sneak in a few added features. For example the latest release (2.3.0.21) added a static OpenNETCF.Net.Dns class with a couple of methods:QueryARecord and ReplaceARecord (the source is itself is actually CE and desktop compliant if you’re interested). These correspond to the APIs DnsQuery_W and DnsReplaceRecordSetW and can be quite useful when your device is on a public network getting assigned a dynamic IP address. (For the record, the MSDN documentation on the APIs is abysmal – and even the headers don’t provide much clarity for usage).

Here’s a quick example of usage:

static void Main(string[] args)
{
  System.Net.IPAddress dnsServer = System.Net.IPAddress.Parse(DNS_ADDRESS);

  try
  {
    string nameToResolve = PC_NAME;

    Console.WriteLine(string.Format(“Getting an A record for ‘{0}’…”, nameToResolve));
    ARecord[] records = Dns.QueryARecord(dnsServer, nameToResolve, QueryOptions.BypassCache);
    Console.WriteLine(string.Format(“rn Name: {0}”, records[0].Name));
    Console.WriteLine(string.Format(” Address: {0}”, records[0].Address.ToString()));
    Console.WriteLine(string.Format(” TTL: {0}”, records[0].TTL));

    string replacementAddress = REPLACE_ADDRESS;
    Console.WriteLine(string.Format(“rnReplacing address {0} with {1}…”, records[0].Address.ToString(), replacementAddress));
    records[0].Address = System.Net.IPAddress.Parse(replacementAddress);
    Dns.ReplaceARecord(dnsServer, records[0], DnsUpdateSecurity.On, UID, DOMAIN, PWD);

    Console.WriteLine(string.Format(“rn Getting an A record for ‘{0}’ again…”, nameToResolve));
    records = Dns.QueryARecord(dnsServer, nameToResolve, QueryOptions.BypassCache);
    Console.WriteLine(string.Format(“rn Name: {0}”, records[0].Name));
    Console.WriteLine(string.Format(” Address: {0}”, records[0].Address.ToString()));
    Console.WriteLine(string.Format(” TTL: {0}”, records[0].TTL));
  }
  catch (DnsException ex)
  {
    Console.WriteLine(string.Format(“rn!! FAILED with error code {0} : ‘{1}'”, ex.ErrorCode, ex.Message));
  }

}

1 thought on “Altering DNS A-Records in the Compact Framework”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s