一、gethostname //获取本地主机名称
用法: char szHost[256];
//获取本地主机名称
::gethostname(szHost, sizeof(szHost));
二、gethostbyname // 通过主机名得到地址信息
用法:
hostent *pHost = ::gethostbyname(szHost);
//打印所有的IP地址
in_addr addr;
for (int i = 0;; i++)
{
char* p = pHost->h_addr_list[i]; //p指向一个32位的IP地址
if (p == NULL)
{
break;
}
memcpy(&addr.S_un.S_addr, p, pHost->h_length
);
char* szIp = ::inet_ntoa(addr);
printf("本机IP地址:%s \n", szIp);
}