3

I'd like to be able to add IP addresses for DNS nameservers on Linux from my C/C++ program. I'm on a somewhat embedded platform with a read-only /etc/resolv.conf. This means I can't simply add a "nameserver xxx.xxx.xxx.xxx" line to the file without a little trickery. Are there any clean ways to do this from code?

I could try symlinking /etc/resolv.conf to a file in tmpfs, but that seems hackish and it feels like something I should be able to do without writing to a file.

Jon
  • 33
  • 1
  • 3

1 Answers1

1

Have a look at nsaddr_list in resolv.conf from your libc.

This question says:

Although not documented, the common way to set the resolver used is to update _res.nsaddr_list.

In uClibc 0.9.31 specifically there is a comment on line 533 in resolv.c describing how this works.

Community
  • 1
  • 1
aaz
  • 5,136
  • 22
  • 18
  • Good find. That value contains my original nameserver value from resolv.conf as expected. However, if I change it, my program still uses the value from resolv.conf. I am using uClibc, though, and I suppose I can't expect them to support all the undocumented features of other libc's. – Jon Feb 18 '11 at 15:13
  • Seems in uClibc you need to call `res_init()` before doing this: see [the comment at line 538](http://git.uclibc.org/uClibc/tree/libc/inet/resolv.c?id=0f4516e32c3a2186e6b6f074cfc6a57bde90e9cc#n538). Let me know if it works and I'll amend the answer. – aaz Feb 18 '11 at 15:40
  • I was calling res_init(), but I'm stuck on [0.9.28](http://git.uclibc.org/uClibc/tree/libc/inet/resolv.c?h=0_9_28), which didn't have that nice comment block you linked to. In both instances, there is a __nameserver variable which feeds the nsaddr_list values from resolv.conf. In my uClibc version, gethostbyname and friends pull directly from __nameserver; it's only the later versions that pull from nsaddr_list. I'll happily accept your answer, as it got me where I needed to be and should actually be correct for most people. – Jon Feb 18 '11 at 19:00
  • Manipulating `nsaddr_list` like suggested is not working for me -- see this question https://stackoverflow.com/questions/55724014 – florgeng Apr 17 '19 at 12:48