Winsock - issue with connecting
I was building a small program to download something from a website once a day. But whenever I run my program, it outputs "WSAConnectByName: returned FALSE with error code 10109", which is WSATYPE_NOT_FOUND according to the list on MSDN (http://msdn.microsoft.com/en-us/library/ms740668%28v=VS.85%29.aspx). I don't really understand what I've done wrong. Does anyone mind finding my error?
#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;
}
Service type is not valid : this altered line of code worked for me.
BOOL fConnect = WSAConnectByName(Socket, const_cast<LPWSTR>(s_lpctszAddress),
TEXT("http"), &dwSOCKADDRLen, &saAddr, NULL, NULL, NULL, NULL);
Per the 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
You need a port/service name as the third parameter.
精彩评论