使用gethostname()得到主机名

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

int gethostname(char *name, size_t len)

这个函数,调用后,会将主机名保存在name里面。而len是name的大小。

以下是例程,编译后只需要运行就知道自己的主机名字了。知道自己名字后,我再调用了一下gethostbyname()来得到主机的一些其他信息。

#include <netdb.h>

#include <sys/socket.h>

int main(int argc, char **argv)

{

struct hostent *hptr;

char **pptr;

char hostname[32];

char str[32];

if( gethostname(hostname,sizeof(hostname)) )

{

printf("gethostname calling error\n");

return 1;

}

printf("localhost name:%s\n",hostname);

if( (hptr = gethostbyname(hostname)) == NULL)

{

printf("gethostbyname calling error\n");

return 1;

}

pptr=hptr->h_addr_list;

for(;*pptr!=NULL;pptr++)

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

return 0;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航