c++ - Winsock 错误代码 10014

标签 c++ windows winsock wsastartup

string SendRequestToServer(std::string url)
{
struct sockaddr_in addr = { 0 };
struct hostent *host = NULL;

// If the URL begins with http://, remove it.
if(url.find("http://") == 0)
    url.erase(0, 7);

// Get the host name.
string hst = url.substr(0, url.find('/', 0));
url.erase(0, url.find("/", 0));

// Connect to the host.
host = gethostbyname(hst.c_str());
if(!host)
{
    Print("%s", "Could not resolve the hostname.");
    int error = WSAGetLastError();
    return "failed";
}
}

看来我经常返回“失败”。以下是我在“返回失败”处的断点被击中时各种变量的值:

url: "/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79%73%74%65%6d% 33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c"

hst: "bgfx.net"

主机:空

错误:10014

这是怎么回事?更重要的是,我该如何修复它?

注意:SendRequestToServer 的原始参数是“bgfx.net/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79 %73%74%65%6d%33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c"

在此之前已调用 WSAStartup。

最佳答案

有些人报告说,如果在应用程序堆栈内存中获取指针,WS 可能会失败并出现此错误。

看起来您使用的是 VS2005 或更新版本,其中 std::string 具有内部 16 个字符长的缓冲区 - 正是这个缓冲区地址被传递到 gethostbyname()。

在将字符串传递给 WS 之前尝试将其复制到堆中:

char *hstSZ = new char[hst.size() + 1];
strcpy(hstSZ, hst.c_str();
host = gethostbyname(hstSZ);
delete[] hstSZ;

如果有帮助,请告诉我们:)

关于c++ - Winsock 错误代码 10014,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/861154/

相关文章:

c++ - C++ 对象构造函数中的 Openmp 使用

c++ - 请求*中的成员*,属于非类类型*

c# - 创建新线程时,不对 GUI 进行更改 (C#)

windows - 如何手动将项目的备份副本导入 Git?

c++ - 检测断开 Winsock C++

c++ - Winsock c++,程序在连接到离线服务器时卡住

c++ - 有什么方法可以避免在 C++ 中使用非法指针吗?

c++ - 使用 PugiXML 进行 XML 解析,无限循环

c++ - Windows 文件 : using both ReadFile and mapping

c - 如何获取 UPnP 的内部 IP、外部 IP 和默认网关