DNS
域名服务(Domain Name Service)
你给它一个容易记忆的某站点的地址, 它给你 IP地址(然后你就可以使用 bind(), connect(), sendto() 或者其它函数)
例如要使用域名连接到一个网站 xuluck.com
$ telnet xuluck.com
telent可以知道连接的目的地址为”47.108.133.125“。
具体的工作过程:
可以调用函数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 - 地址的正式名称。
h_aliases - 空字节-地址的预备名称的指针。
h_addrtype -地址类型; 通常是AF_INET。
h_length - 地址的比特长度。
h_addr_list - 零字节-主机网络地址指针。网络字节顺序。
h_addr - h_addr_list中的第一地址。
gethostbyname() 成功时返回一个指向结构体 hostent 的指针,或者 是个空(NULL) 指针。
举例使用:
#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()。
相当简单,你只是传递一个保存机器名的字符串(例如 “xuluck.com”) 给gethostbyname(),然后从返回的数据结构 struct hostent 中获取信息。
唯一也许让人不解的是输出 IP 地址信息。h->h_addr 是一个 char * , 但是inet_ntoa() 需要的是 struct in_addr。因此,我转换 h->h_addr 成 struct in_addr *,然后得到数据。