关于gethostname函数失败的问题

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

你可能感兴趣的:(C++,Visual)