DNS--You say "whitehouse.gov", I say "198.137.240.100"
如果你不知道 DNS 的意思,那么我告诉你,他代表"域名服务 (Domain Name Service)"。 他主要的功能是:你给他一个容易记忆的某站点的地址,他给你 IP 地址(然后你就可以 使用 bind(), connect(), sendto() 或者其他函数。)当一个人 输入:
$ telnet whitehouse.gov
telnet 能知道他将连接 (connect()) 到 "198.137.240.100"。
但是这是如何工作的呢? 你可以调用函数 gethostbyname():
- #include <netdb.h>
- struct hostent *gethostbyname(const char *name);
很明白的是,他返回一个指向 struct hostent 的指针。这个数据结构是 这样的:
- struct hostent {
- char *h_name;
- char **h_aliases;
- int h_addrtype;
- int h_length;
- char **h_addr_list;
- };
- #define h_addr h_addr_list[0]
这里是这个数据结构的详细资料: struct hostent:
h_name - Official name of the host.
h_aliases - A NULL-terminated array of alternate names for the host.
h_addrtype - The type of address being returned; usually AF_INET.
h_length - The length of the address in bytes.
h_addr_list - A zero-terminated array of network addresses for the host. Host addresses are in Network Byte Order.
h_addr - The first address in h_addr_list.
gethostbyname() 成功时返回一个指向 struct hostent 的 指针,或者是个空 (NULL) 指针。(但是和以前不同,errno 不设置,h_errno 设置错误信息。请看下面的 herror()。)
但是如何使用呢? 这个函数可不象他看上去那么难用。
这里是个例子:
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <netdb.h>
- #include <sys/types.h>
- #include <netinet/in.h>
-
- int main(int argc, char *argv[])
- {
- struct hostent *h;
-
- if (argc != 2) {
- fprintf(stderr,"usage: getip address\n");
- exit(1);
- }
-
- if ((h=gethostbyname(argv[1])) == NULL) {
- herror("gethostbyname");
- exit(1);
- }
-
- printf("Host name : %s\n", h->h_name);
- printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr)));
-
- return 0;
- }
在使用 gethostbyname() 的时候,你不能用 perror() 打印错误信息(因 为 errno 没有使用),你应该调用 herror()。
相当简单,你只是传递一个保存机器名的自负串(例如 "whitehouse.gov") 给 gethostbyname(),然后从返回的数据结构 struct hostent 中 收集信息。
唯一让人迷惑的是打印 IP 地址信息。h->h_addr 是一个 char *, 但是 inet_ntoa() 需要的是 struct in_addr。因此,我 转换 h->h_addr 成 struct in_addr *,然后得到数据。
(haiyan0106) |