标签:android
Android DNS 代码都在bionic/libc/netbsd中
(虽然netbsd 是个废弃的项目,但dns功能部分代码被 Android用上了)
netbsd 代码晦涩难懂,只有一边写程序,一边打log验证
照抄了一个简单程序, 在android 下面用 mmm 编译可以得到 py_getaddr 可执行文件, 用adb 登陆到 devices 再到 system/bin 下去执行
payne@payne-desktop:~/njb/getaddr$ cat py_getaddr.c #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s hostname\n", argv[1]); exit(1); } struct addrinfo *answer, hint, *curr; char ipstr[16]; bzero(&hint, sizeof(hint)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; int ret = getaddrinfo(argv[1], NULL, &hint, &answer); if (ret != 0) { fprintf(stderr,"getaddrinfo: &s\n", gai_strerror(ret)); exit(1); } for (curr = answer; curr != NULL; curr = curr->ai_next) { inet_ntop(AF_INET, &(((struct sockaddr_in *)(curr->ai_addr))->sin_addr), ipstr, 16); printf("%s\n", ipstr); } freeaddrinfo(answer); exit(0); }
cat Android.mk LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= py_getaddr.c LOCAL_MODULE := py_getaddr LOCAL_STATIC_LIBRARIES := libcutils libc include $(BUILD_EXECUTABLE)
_files_getaddrinfo 是读取/system/etc/hosts 检索
_dns_getaddrinfo 是访问dns server
在访问构造 dns 访问的时候,如何找到 dns server, 原来在 __res_get_state 调用返回 __res_state (这个复杂的结构定义在 bionic/libc/private/resolv_private.h#__res_state )
在调用过程中 __res_vinit 使用了系统设置的 8.8.8.8 nameserver (jeallybean 代码在bionic/libc/netbsd/resolv/res_init.c#339)
之后res_queryN 用 res_nmkquery 构造dns 查询,并用 res_nsend 发送查询,并得到返回结果。
运行程序和 log 的打印结果如下:
py_getaddr sohu.com
======================= _files_getaddrinfo
======================= _dns_getaddrinfo
=========== getaddrinfo cp 8.8.8.8, subf 53
================ res_searchN sohu.com
================ res_querydomainN name sohu.com, domain (null)
================ res_queryN sohu.com
;; res_nmkquery(QUERY, sohu.com, IN, A)
================getanswer sohu.com
220.181.90.240
123.125.116.19
标签:android
原文地址:http://blog.csdn.net/span76/article/details/41478555