工作中遇到个奇怪的问题,就是函数gethostbyname在2.6.18-308.el5PAE编译的版本在2.6.32-431.el6.x86_64上运行,就无法获取linux主机的主机名,采用的函数代码是从网络上
复制的:
#include <netdb.h>
#include <sys/socket.h>
#include <stdio.h>
#include<string.h>
#include<errno.h>
int main(int argc, char **argv)
{
char *ptr, **pptr;
struct hostent *hptr;
char str[32];
ptr = argv[1];
char*message;
if((hptr = gethostbyname(ptr)) == NULL)
{
printf(" gethostbyname error for host:%s\n", ptr);
message=strerror(errno);
printf("Mesg:%s\n",message);
return 0;
}
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;
for(; *pptr!=NULL; pptr++)
printf(" address:%s\n",
inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
printf(" first address: %s\n",
inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
break;
default:
printf("unknown address type\n");
break;
}
return 0;
}
~
"1.c" 43L, 1107C 已写入
[test]:[/dsg11/cxf]$ gcc 1.c -o host_test
[test]:[/dsg11/cxf]$ ./host_test test
挺好用的,解决了工作中的问题,记录下