[C++]gethostname回傳錯誤代碼?

同事在寫VC視窗程式時,下了一段code,主要用途在於獲取自己的IP,如下:
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錯誤或沒有初始化造成。解法也很簡單:

  1. 若是MFC - 在InitInstance()中加上AfxSocketInit()
  2. 其他 - 呼叫WSAStartup(),WSACleanup()

解法1會去調用WSAStartup(),但不需要自行呼叫WSACleanup(),因為MSDN說:This function also ensures that WSACleanup is called for you before the application terminates.

0 意見:

搜尋此網誌

總網頁瀏覽量

TK呱呱

Made with by TK