Linux下网络相关结构体 struct hostent
参考书籍:《UNIX环境高级编程》
参考链接:
http://www.cnblogs.com/cxz2009/archive/2010/11/19/1881611.html
http://www.yeolar.com/note/2012/05/18/linux-socket/
一、简介
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]
定义如下:
1.h_name
表示的是主机的规范名。例如www.google.com的规范名其实是www.l.google.com。
2.h_aliases
表示的是主机的别名.www.google.com就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
3.h_addrtype
表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是pv6(AF_INET6)
4.h_length
表示的是主机ip地址的长度
5.h_addr_lisst
表示的是主机的ip地址,注意,这个是以网络字节序存储的。因此需要通过inet_ntoa(仅用于IPv4地址)或者inet_ntop(支持IPv4和IPv6)
二、代码展示
1)相关函数
与此结构体相关的函数:
/* 获取文件的下一个hostent结构* @return 成功返回指向hostent结构的指针,出错返回NULL */
struct hostent *gethostent(void);
/* gethostent的可重入版本,自设缓冲 */
int gethostent_r(struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop);
/* 回到文件开头 */
void sethostent(int stayopen);
/* 关闭文件 */
void endhostent(void);/* 通过主机名或地址查询hostent结构* @return 成功返回指向hostent结构的指针,出错返回NULL */
struct hostent *gethostbyname(const char *name);struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);
2) gethostbyname
gethostbyname用于通过给定的域名或者主机名获取到IP地址。
1.代码
#include
#include
#include
#include 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);
printf("test\n");/* 根据地址类型,将地址打出来 */
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)));
//printf("address:%s\n", inet_ntoa(*(struct in_addr*)(*pptr)));
}break;
default:
printf("unknown address type\n");
break;
}return 0;
}
其中,inet_ntop的函数原型如下:
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。返回指向dst的一个指针。如果函数调用错误,返回值是NULL.
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
