您的位置:首页 > 其它

关于gethostname函数失败的问题

2014-05-07 10:36 429 查看
调用gethostname之前, 要先调用WSAStartup才可以, 否则gethostname会失败!

下面是正确的代码

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <Winsock2.h>

#include <windows.h>

#pragma comment(lib, "Ws2_32")

int main()

{

WSADATA wsData;

::WSAStartup(MAKEWORD(2,2), &wsData);

char szIP[32] = {0};

char szHostName[32] = {0};

int iResult = ::gethostname(szHostName, sizeof(szHostName));

if (iResult != 0)

{

  printf("error/n");

  return -1;

}

printf("%s/n", szHostName);

hostent *pHost = ::gethostbyname(szHostName);

::WSACleanup();

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: