Compile C with function gethostbyname to static linked error

非 Y 不嫁゛ 提交于 2019-12-06 02:31:36

Short Explanation

DNS lookup in glibc requires /lib/libnss_dns.so.2 , which is not available on Android.

Another difference is that Android stores the DNS settings /system/etc/resolv.conf , and native Android apps built with the bionic C library will look there to find the DNS servers to query. Applications built with glibc will look in /etc/resolv.conf , which doesn't exist on Android.

Longer Explanation

You've built the binaries using glibc, while Android uses the bionic C library.

This should for the most part be fine when linking to a libc statically, as I'm not aware of severe enough changes in the android kernel to break simple user land apps. You're supposed to use the Android NDK for building android native apps though,

There's however a few things that goes wrong when linking to glibc statically. Certain functions in glibc, e.g. for looking up user info, host names and other things that's normally configured in /etc/nsswitch.conf calls out to other shared libraries to actually do the work. This happens regardless of whether you link to glibc itself statically or not. These files are usually the /lib/libnss_* files found on glibc systems.

Most of those shared libraries are part of glibc, and would be installed on glibc systems. But they're not available on Android. Applications relying the funcions that uses these helper shared libs not work properly when these shared libraries are available - gethostbyname() is one of them, as for normal DNS queries it requres /lib/libnss_dns.so.2

for the explanation refer to nos reply, for the solution follow these steps:

  • download android NDK from here: https://developer.android.com/ndk/downloads/index.html (I used linux 64bit)
  • unzip android-ndk-r13b-linux-x86_64.zip
  • enter in the just unpacked directory
  • launch ./build/tools/make_standalone_toolchain.py to see possible options
  • e.g. ./build/tools/make_standalone_toolchain.py --arch arm --api 9
  • the tool will build arm-linux-androideabi.tar.bz2 for you
  • unpack with tar xjvf arm-linux-androideabi.tar.bz2
  • it will create ./arm-linux-androideabi directory
  • now you can compile with ./arm-linux-androideabi/bin/arm-linux-androideabi-gcc yourprog.c -o yourprog -pie
  • -pie is needed for Android >= 5
  • your generated executable is native and the resolver will work as expected
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!