Winsock 2 - Connect To Website

Hey all, I'm trying to send a GET request to a website server. Just testing out some stuff. Anyway I got most of this code from a tutorial on the internet. I understand most of it, problem is for some reason I can't get the socket to connect to the server. Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

#include <iostream>
#include <winsock2.h>
#include <windows.h>

using namespace std;

const int  REQ_WINSOCK_VER   = 2;   // Minimum winsock version required
const char DEF_SERVER_NAME[] = "www.yahoo.com";
const int  SERVER_PORT       = 80;
const int  TEMP_BUFFER_SIZE  = 128;

const char HEAD_REQUEST_PART1[] =
{
    "HEAD / HTTP/1.1\r\n"           // Get root index from server
    "Host: "        // Specify host name used
};

const char HEAD_REQUEST_PART2[] =
{
    "\r\n"                          // End hostname header from part1
    "User-agent: HeadReqSample\r\n" // Specify user agent
    "Connection: close\r\n"         // Close connection after response
    "\r\n"                          // Empty line indicating end of request
};

// IP number typedef for IPv4
typedef unsigned long IPNumber;

bool RequestHeaders(const char* pServername);

class HRException
{
public:
    HRException() :
         m_pMessage("") {}
    virtual ~HRException() {}
    HRException(const char *pMessage) :
         m_pMessage(pMessage) {}
    const char * what() { return m_pMessage; }
private:
    const char *m_pMessage;
};

int main()
{
    int iRet = 1;
    WSADATA wsaData;

    cout << "Initializing winsock... ";

    if (WSAStartup(MAKEWORD(REQ_WINSOCK_VER,0), &wsaData)==0)
    {
        // Check if major version is at least REQ_WINSOCK_VER
        if (LOBYTE(wsaData.wVersion) >= REQ_WINSOCK_VER)
        {
            cout << "initialized.\n";

            // Set default hostname:
            const char* pHostname = DEF_SERVER_NAME;

            iRet = !RequestHeaders(pHostname);
        }
        else
        {
            cerr << "required version not supported!";
        }

        cout << "Cleaning up winsock... ";

        // Cleanup winsock
        if (WSACleanup()!=0)
        {
            cerr << "cleanup failed!\n";
            iRet = 1;
        }
        cout << "done.\n";
    }
    else
    {
        cerr << "startup failed!\n";
    }

    cout << WSAGetLastError();
    return iRet;
}

IPNumber FindHostIP(const char *pServerName)
{
    HOSTENT *pHostent;

    // Get hostent structure for hostname:
    if (!(pHostent = gethostbyname(pServerName)))
            throw HRException("could not resolve hostname.");

    // Extract primary IP address from hostent structure:
    if (pHostent->h_addr_list && pHostent->h_addr_list[0])
        return *reinterpret_cast<IPNumber*>(pHostent->h_addr_list[0]);

    return 0;
}

void FillSockAddr(sockaddr_in *pSockAddr, const char *pServerName, int portNumber)
{
    // Set family, port and find IP
    pSockAddr->sin_family = AF_INET;
    pSockAddr->sin_port = htons(portNumber);
    pSockAddr->sin_addr.S_un.S_addr = FindHostIP(pServerName);
}

bool RequestHeaders(const char* pServername)
{
    SOCKET      hSocket = INVALID_SOCKET;
    char        tempBuffer[TEMP_BUFFER_SIZE];
    sockaddr_in sockAddr = {0};
    bool        bSuccess = true;

    try
    {
        // Lookup hostname and fill sockaddr_in structure:
        cout << "Looking up hostname " << pServername << "... ";
        FillSockAddr(&sockAddr, pServername, SERVER_PORT);
        cout << "found.\n";

        // Create socket
        cout << "Creating socket... ";
        if ((hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
            throw HRException("could not create socket.");
        cout << "created.\n";

        if (hSocket!=INVALID_SOCKET)
            closesocket(hSocket);

        // Connect to server
        cout << "Attempting to connect to " << inet_ntoa(sockAddr.sin_addr)
             << ":" << SERVER_PORT <<  "... ";

        if (connect(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
            throw HRException("could not connect.");

        cout << "connected.\n";

        cout << "Sending request... ";

        // send request part 1
        if (send(hSocket, HEAD_REQUEST_PART1, sizeof(HEAD_REQUEST_PART1)-1, 0)==SOCKET_ERROR)
            throw HRException("failed to send data.");

        // send hostname
        if (send(hSocket, pServername, lstrlen(pServername), 0)==SOCKET_ERROR)
            throw HRException("failed to send data.");

        // send request part 2
        if (send(hSocket, HEAD_REQUEST_PART2, sizeof(HEAD_REQUEST_PART2)-1, 0)==SOCKET_ERROR)
            throw HRException("failed to send data.");

        cout << "request sent.\n";

        cout << "Dumping received data...\n\n";
        // Loop to print all data
        while(true)
        {
            int retval;
            retval = recv(hSocket, tempBuffer, sizeof(tempBuffer)-1, 0);
            if (retval==0)
            {
                break; // Connection has been closed
            }
            else if (retval==SOCKET_ERROR)
            {
                throw HRException("socket error while receiving.");
            }
            else
            {
                // retval is number of bytes read
                // Terminate buffer with zero and print as string
                tempBuffer[retval] = 0;
                cout << tempBuffer;
            }
        }

    }
    catch(HRException e)
    {
        cerr << "\nError: " << e.what() << endl;
        bSuccess = false;
    }

    return bSuccess;
}


And the exception is thrown here:

1
2
3
4
5
6
7
8

// Connect to server
        cout << "Attempting to connect to " << inet_ntoa(sockAddr.sin_addr)
             << ":" << SERVER_PORT <<  "... ";

        if (connect(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr))!=0)
            throw HRException("could not connect.");


Can anyone see the problem here? I turned off my Norton firewall and Windows firewall but still no luck.

Any help would be awesome!!!

Thanks in advance, Nick :)

Last edited on
That's a lot of code for something so basic. It might help if you took some time to learn about TCP/IP programming, then you'd be better placed to understand what you have.

Just to be clear, you can't write network code without understanding networking to some extent.

http://www.cs.aau.dk/~bnielsen/Tricks/v3.dist/examples/
Hey thanks heaps for the link, that stuff is great!

I also found the stupid error in the code, I really should have tried harder before turning to these forums lol I was closing the socket before connecting to the server. Guess that's what I get for cutting and pasting bits and pieces of code.

Thanks again,

Nick :)
Topic archived. No new replies allowed.