c++ - Winsock - 连接问题

标签 c++ windows winsock

我正在构建一个小程序,每天从网站下载一些东西。但是每当我运行我的程序时,它都会输出“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/

相关文章:

c++ - 将内存数据库保存到磁盘

ruby - 使用 Ruby 设置 Windows 壁纸

windows - 突然之间,perl 脚本不起作用,除非我在它们前面加上 "perl"并提供脚本的完整路径

c++ - 套接字程序 Python vs C++ (Winsock)

windows - 故障转储中的套接字调查

c++ - 根据分量 ​​1、2(和 3)对空间(2D/3D) vector 的 vector 进行排序

c++ - 多重映射迭代器不工作

c++ - 有什么方法可以从数据类型调用构造函数(或任何函数/方法)而无需通过两个模板化函数?

windows - 在 Windows 中删除符号链接(symbolic link)

c++ - winsock:使用 localhost (127.0.0.1) 时连接失败并出现错误 10049