现在的位置: 首页 > 编程语言 > 正文

关于gethostname函数失败的问题

2018年09月16日 编程语言 ⁄ 共 472字 ⁄ 字号 评论关闭

调用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;
}

抱歉!评论已关闭.