问题
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";
}
}
It seems I'm returning "failed" quite frequently. Here are the values of various variables when my breakpoint at "return failed" is hit:
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"
host: NULL
error: 10014
What's going on here? More importantly, how can I fix it?
NOTE: The original parameter to SendRequestToServer is "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 HAS been called before this.
回答1:
Some people report that WS can fail with this error if got pointer inside application stack memory.
It looks like you are using VS2005 or newer where std::string has internal 16 chars long buffer - and exactly this buffer address was passed into gethostbyname().
Try to copy your string to heap before passing it to WS:
char *hstSZ = new char[hst.size() + 1];
strcpy(hstSZ, hst.c_str();
host = gethostbyname(hstSZ);
delete[] hstSZ;
And let us know, if it helped :)
回答2:
Error 10014 will also be returned for addresses that aren't properly aligned even when the address is valid. That means that on 32-bit systems, the addresses have to be multiples of 4, and on 64-bit systems, they must be multiples of 8.
The X86 and X64 chips normally tolerate misaligned structures with a small performance penalty, but operating system calls such as TransmitPackets often do not.
I discovered this while debugging a TransmitPackets problem that seemed quite random. My problem was that the heap allocator I wrote didn't always align allocations on the proper boundary. Fixing the heap allocator elimininated the problems.
回答3:
10014 is WSAEFAULT. You will notice from the documentation that this means "The name parameter is not a valid part of the user address space." I would check what hst.c_str() is returning.
来源:https://stackoverflow.com/questions/861154/winsock-error-code-10014