gethostbyname无法获得hosts文件下的正确IP
remoteHost = gethostbyname(cip);
if (remoteHost != NULL)
{
//方法一:
memcpy(&HostAddr.sin_addr.S_un.S_addr ,&remoteHost->h_addr_list[0],remoteHost->h_length);
ipstr=inet_ntoa(HostAddr.sin_addr);
printf("IP:%s",ipstr);
/*//方法二:
pptr = remoteHost->h_addr_list;
l1 = inet_addr(*pptr);
ipstr = inet_ntoa(addr1);
printf("official hostname:%s\n",remoteHost->h_name);
printf(" alias:%s\n",*pptr);
for(;*pptr!=NULL;pptr++)
printf("IP address: %s\n", inet_ntoa(addr1));
*/
两个办法都无法获得正确IP,请指正。
[解决办法]
Hostent = (struct hostent*)malloc(sizeof(struct hostent));
Hostent = gethostbyname(HostName);
int i=0;
char **ptr=Hostent->h_addr_list;
for(; ptr[i];i++)
{
printf("\n\n第%d个网络接口:\n", i+1 );
printf("IP地址:%s\n", inet_ntoa(*(IN_ADDR*)ptr[i]));
}
[解决办法]
CString CTestDlg::GetIPAddress(const CString &sHostName){ CString strIP = ""; struct hostent FAR *lpHostEnt = gethostbyname (sHostName); if (lpHostEnt == NULL) return ""; LPSTR lpAddr = lpHostEnt->h_addr_list[0]; if (lpAddr) { struct in_addr inAddr; memmove (&inAddr, lpAddr, 4); strIP = inet_ntoa (inAddr); if (sIPAddress.IsEmpty()) return ""; } else return ""; return strIP;}