Compile a static binary which code there a function gethostbyname

心不动则不痛 提交于 2019-11-28 07:31:50
Borealid

What you are asking for is going to be very difficult.

See this StackOverflow question about getaddrinfo. Basically, underneath getaddrinfo/gethostbyname is glibc's NSS layer. This allows a sysadmin to say "use DNS for resolving hostnames to IP addresses", or "use LDAP", or "don't use anything other than /etc/hosts". This control is at runtime; the sysadmin can at any point change the way hostnames are resolved to IPs.

Because of this flexibility, all of the name-resolution calls in glibc use helper libraries (plugins, basically) to do the grunt work of resolution. There's one shared library for LDAP addressing, one for files, one for DNS, one for YP, and so on and so on.

If you want your program to be 100% statically linked, you're going to have to go elsewhere (NOT gethostbyname) to convert a hostname to an IP address. You could do this with a resolver library like uDNS (not this exact one - there are similar tools available), but you should keep in mind that your binary is not going to do the right thing on systems which are configured not to use DNS!

Instead, I would recommend just leaving the program (technically) dynamically linked. If you really want to make sure it will run on any platform, you could even ship glibc with the binary - although doing this would require LGPL conformance. Leaving this one dynamic link in place will only mean you won't work on systems with the wrong glibc version - not a huge compatibility issue.

Speaking of license compliance, it's worth noting that if you statically link glibc, you most likely have to ship the source code for your entire application to comply with glibc's LGPL license. I am not a lawyer, and this is not qualified legal advice, but reading the LGPL makes it very clear that applications statically linking glibc must be open-source. See this StackOverflow question on the topic.

kimi shi

I get the same warning and to fix it I recompiled glibc. Turn on switch --enable-static-nss when configuring to get it to work.

I have 2 answers -

  1. Keep the main part of your program statically linked, and separate out a single function program to just call gethostbyname(). Allow the latter to be dynamically linked. Using fork then exec execute this separate program to get the address for a domain name. Instead of fork then exec you could use system() though it takes longer (a whole millisecond) that should not be of concern since you're searching nameservers on the internet anyway, which takes a time.

  2. Write the source code to do the DNS, as I have done. Compile it into an archive (.a) and have it searched in the static linking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!