我正在构建一个小程序,每天从网站下载一些东西。但是每当我运行我的程序时,它都会输出“WSAConnectByName:返回 FALSE,错误代码 10109”,根据 MSDN 上的列表,这是 WSATYPE_NOT_FOUND (http://msdn.microsoft.com/en-us/library/ms740668%28v= VS.85%29.aspx)。我真的不明白我做错了什么。有人介意发现我的错误吗?
#include <cstdio>
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#include <windows.h>
static const TCHAR s_lpctszAddress[] = TEXT("www.google.com");
int main(int argc, char* argv[])
{
using namespace std;
using namespace boost;
WSADATA wsaData;
int iWSAStartup = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (!iWSAStartup)
{
SOCKET Socket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
if (Socket != INVALID_SOCKET)
{
INT iSize = sizeof(s_lpctszAddress);
SOCKADDR saAddr;
DWORD dwSOCKADDRLen = sizeof(saAddr);
BOOL fConnect = WSAConnectByName(Socket, const_cast<LPWSTR>(s_lpctszAddress), TEXT("/"), &dwSOCKADDRLen, &saAddr, NULL, NULL, NULL, NULL);
if (fConnect == TRUE)
{
cout << "Success!";
}
else
{
cout << format("WSAConnectByName: returned FALSE with error code %1%.") % WSAGetLastError() << endl;
}
}
else
{
cout << format("WSASocket: returned INVALID_SOCKET with error %1%.") % WSAGetLastError() << endl;
}
}
else
{
cout << format("WSAStartup: returned %1% with error %2%.") % iWSAStartup % WSAGetLastError() << endl;
}
return 0;
}
最佳答案
服务类型无效:此更改后的代码行对我有效。
BOOL fConnect = WSAConnectByName(Socket, const_cast<LPWSTR>(s_lpctszAddress),
TEXT("http"), &dwSOCKADDRLen, &saAddr, NULL, NULL, NULL, NULL);
根据 Microsoft docs :
A service name is a string alias for a port number. For example, “http” is an alias for port 80 defined by the Internet Engineering Task Force (IETF) as the default port used by web servers for the HTTP protocol. Possible values for the servicename parameter when a port number is not specified are listed in the following file:
%WINDIR%\system32\drivers\etc\services
关于c++ - Winsock - 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393696/