The information of the host in Linux is usually stored in/etc/hosts, and we can read the file information through the function gethostent.
Note that the address of the struct Hostent struct object returned is a static buffer, the address of this static buffer is fixed, and when Gethostent is called multiple times, the
Will overwrite the contents of the front buffer, and the contents of the buffer pointed to by the multiple reads are consistent, which helps to preventThere is a memory leak caused by releasing memory.
#include<netdb.h>
#include<stdio.h>
void getHostent()
{
struct hostent* host1;
host1 = gethostent();
struct hostent* host2;
host2 = gethostent();
printf("host1:%x,host2:%x\n",host1,host2);
printf("h_name:%s\n",host1->h_name);
///////
}
int main()
{
getHostent();
return 0;
}
If the Hosts file is not open when calling Gethostent, the function opens the file, and if you want to close the file, you can use the Endhostent function:
From for notes (Wiz)
Linux Get host information