gethostbyname将返回一个struct hostent的指针,这个结构定义如下:
struct hostent
{
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
#include<stdio.h>
#include<unistd.h>
#include<netdb.h>
#include<arpa/inet.h>
int get_hostip()
{
char name[100] = {0};
int ret = gethostname(name, 100);
if (ret!=0)
{
printf("get host name failed!");
return -1;
}
struct hostent * pHost = gethostbyname(name);
if (pHost == NULL)
{
printf("get host byname failed/n");
return -1;
}
printf("host name = %s/n", pHost->h_name);
char ** adder = pHost->h_addr_list;
while(*adder)
{
printf("adder = %s/n", inet_ntoa(*(struct in_addr *)*adder));
adder++;
}
return 0;
}
int main()
{
get_hostip();
return 0;
}