/* Linux C gethostbyname获得本机IP 结果全是127.0.0.1,没有获得固定的IP, linux主机有固定IP,这个怎么解决*/
char hostname[1024]={0};
struct hostent*ent=NULL;
char**ip=NULL;
if(0!=gethostname(hostname,sizeof(hostname)))
{
perror("");
return -1;
}
if(NULL==(ent=gethostbyname(hostname)))
{
perror("");
return -1;
}
for(ip=ent->h_addr_list;*ip!=NULL;ip++)
{
printf("%s\n",inet_ntoa(*(struct in_addr*)*ip));
}
#include
#include
#include
int main(int argc, char **argv)
{
char *ptr, **pptr;
struct hostent *hptr;
char str[32];
ptr = argv[1];
if((hptr = gethostbyname(ptr)) == NULL)
{
printf(" gethostbyname error for host:%s\n", ptr);
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)));
// inet_ntop():对IPv4和IPv6地址都能进行处理,将地址由二进制数转换为点分十进制
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;