大龙的博客

常用链接

统计

最新评论

hostent结构体

使用这个东西,首先要包含2个头文件:
#include <netdb.h>
#include <sys/socket.h>

struct hostent *gethostbyname(const char *name);
这个函数的传入值是域名或者主机名,例如"
www.google.com","wpc "等等。
传出值,是一个hostent的结构(如下)。如果函数调用失败,将返回NULL。

struct hostent {
  char  *h_name;
  char  **h_aliases;
  int   h_addrtype;
  int   h_length;
  char  **h_addr_list;
  };
解释一下这个结构:
其中,
  char *h_name 表示的是主机的规范名。例如
www.google.com 的规范名其实是 www.l.google.com
  char   **h_aliases 表示的是主机的别名。
www.google.com 就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
  int   h_addrtype 表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)
  int   h_length 表示的是主机ip地址的长度
  int   **h_addr_lisst 表示的是主机的ip地址,注意,这个是以网络字节序存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。

const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。
这个函数,其实就是返回指向dst的一个指针。如果函数调用错误,返回值是NULL。

 

下面是例程,有详细的注释。

#include <netdb.h>
#include <sys/socket.h>

int main(int argc, char **argv)
{
 char *ptr,**pptr;
 struct hostent *hptr;
 char str[32];
 /* 取得命令后第一个参数,即要解析的域名或主机名 */
 ptr = argv[1];
 /* 调用gethostbyname()。调用结果都存在hptr中 */
 if( (hptr = gethostbyname(ptr) ) == NULL )
 {
  printf("gethostbyname error for host:%s\n", ptr);
  return 0; /* 如果调用gethostbyname发生错误,返回1 */
 }
 /* 将主机的规范名打出来 */
 printf("official hostname:%s\n",hptr->h_name);
 /* 主机可能有多个别名,将所有别名分别打出来 */
 for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
  printf("  alias:%s\n",*pptr);
 /* 根据地址类型,将地址打出来 */
 switch(hptr->h_addrtype)
 {
  case AF_INET:
  case AF_INET6:
   pptr=hptr->h_addr_list;
   /* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */
   for(;*pptr!=NULL;pptr++)
    printf("  address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
   break;
  default:
   printf("unknown address type\n");
   break;
 }
 return 0;
}

posted on 2006-11-07 17:00 大龙 阅读(22398) 评论(5)  编辑 收藏 引用

评论

# re: hostent结构体 2007-04-15 22:55 杨帅

inet_ntop()好像windows和linux都没有这个函数吧
我打印地址为:
printf("address: %s\n", inet_ntoa(*(in_addr*)(*pptr) ) );
总感觉有点麻烦:先把char*转化为in_addr*,然后用inet_nota转化为本地的字符串。
我有个疑问是,既然*pptr是char*,为什么对它直接打印会出现乱码。
我觉的因该把h_addr_list定义为void**更好些  回复  更多评论   

# re: hostent结构体[未登录] 2007-11-19 16:07 yy

回复:inet_ntop()好像windows和linux都没有这个函数吧

是不是inet_ntoh()??  回复  更多评论   

# re: hostent结构体 2008-01-10 13:29

请教:
1.这个hostent是在linux底下的结构体吗?
2.是不是网络层在给数据包添加Ip包头的时候,在填写源IP字段时的依据也是这个hostent结构体中的 char **h_addr_list ?
急切的想得到答复,我的邮箱地址 : shaozy@snnu.edu.cn  回复  更多评论   

# re: hostent结构体[未登录] 2008-10-26 21:10 xixi

我觉得你关于inet_ntop()的作用理解错了:
It should be "similar to inet_ntoa()" but working with IPV4 and IPv6"
,besides, it used to map a 32-bit integer(an IP address in network byte order) to an ASCII string in dotted decimal format.  回复  更多评论   

# re: hostent结构体[未登录] 2010-03-07 11:32 bingo

printf(" address:%s\n", (char *)inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));

这样把  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理