int hostIPAddr;
if(!::gethostname(m_hostname,sizeof(m_hostname)))
{
struct hostent *m_hostinfo = ::gethostbyname(m_hostname);
if(m_hostinfo != NULL)
{
struct in_addr *m_ip = (struct in_addr*)m_hostinfo->h_addr_list[0];
hostIPAddr = ntohl(m_ip->S_un.S_addr);
}
else
{
hostIPAddr = 0x7f000001;//127.0.0.1
}
}
然後就一直發現無法得到想要值,對照了一下,發現造成錯誤原因很簡單--SOCKET_ERROR。Socket錯誤或沒有初始化造成。解法也很簡單:
- 若是MFC - 在InitInstance()中加上AfxSocketInit()
- 其他 - 呼叫WSAStartup(),WSACleanup()
解法1會去調用WSAStartup(),但不需要自行呼叫WSACleanup(),因為MSDN說:This function also ensures that WSACleanup is called for you before the application terminates.
0 意見:
張貼留言