关于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;
} 
本文为“技术点滴”的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注