gpt4 book ai didi

C++: gethostname() 失败

转载 作者:行者123 更新时间:2023-11-28 00:26:18 27 4
gpt4 key购买 nike

我需要获取我正在使用的系统主机名 gethostname功能

但是它失败了,错误代码是 10093

WSANOTINITIALISED 10093

Successful WSAStartup not yet performed. Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

下面是我的程序代码:

#include <Winsock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#pragma comment(lib, "Ws2_32.lib")

int main()
{
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
int err = WSAGetLastError();
}

什么可能导致此失败?


编辑

在 gethostname 函数调用之前添加以下代码解决了问题。

if (WSAStartup (MAKEWORD(2,2), &WSAData) != 0) 
{
MessageBox (NULL, TEXT("WSAStartup failed!"), TEXT("Error"), MB_OK);
return FALSE;
}

最佳答案

它写在您发布的链接中:

A successful WSAStartup call must occur before using this function.

调用WSAStartup,检查其返回码,如果一切正常,调用gethostname

关于C++: gethostname() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24860955/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com