因特网域名

因特网客户端和服务器互相通信时使用的ip地址,然而对于因特网用户来说,记住这么多数字是非常有难度的,所以因特网产生了一种更人性化,易记的域名,当我们访问域名时,系统根据域名转换为相应的ip地址。域名的产生对因特网的快速发展起着至关重要的作用。
下面我们就介绍因特网的域名相关函数:
相关头文件:
#include < netdb.h>
struct hostent *gethostbyname(const char *name);
struct hostent *gethostbyaddr(const char *addr,int len,0);
参数说明:
name:域名
addr:ip地址 len :ip地址的字节长度
返回值:
如果失败,则返回一个NULL指针
如果成功,则返回一个DNS结构体

struct hostent{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
int ** h_addr_list;
}


例 :
实验环境:mac OS


#include < stdio.h>
#include < netdb.h>
#include < arpa/inet.h>
int main(i nt argc,char **argv)
{
printf(“this is dns programes!\n”);
char **pp;
struct in_addr addr;
struct hostent *hostp;

if(argc !=2)
{
printf(“参数错误!\n”);
return 0;
}

if(inet_aton(argv[1],&addr) !=0)
hostp = gethostbyaddr((const char *)&addr,sizeof(addr),AF_INET);
else
hostp = gethostbyname(argv[1]);

printf(“official hostname:%s\n”,hostp->h_name);

for(pp = hostp->h_aliases;*pp !=NULL;pp++)
printf(“alias:%s\n”,*pp);

for(pp=hostp->h_addr_list;*pp !=NULL;pp++){
addr.s_addr =*((unsigned int *)*pp);
printf(“address:%s\n”,inet_ntoa(addr));
}

return 1;
}


运行效果图:
shenyetekiAir:c shenye$ ./dns localhost
this is dns programes!
official hostname:localhost
address:127.0.0.1

shenyetekiAir:c shenye$ ./dns maomao365.com
this is dns programes!
official hostname:maomao365.com
address:61.54.47.69

shenyetekiAir:c shenye$ ./dns
this is dns programes!
参数错误!
shenyetekiAir:c shenye$ ./dns cs.mit.edu
this is dns programes!
official hostname:eecs.mit.edu
alias:cs.mit.edu
address:18.62.1.6
shenyetekiAir:c shenye$ ./dns alo.com
this is dns programes!
official hostname:alo.com
address:211.106.65.111
address:211.106.65.112