I am working on a function that will (when it’s finished) return the output of an html page. I just got help from StackOverFlow with understanding how recv works, and I am now at a point where I am finishing up the function. The problem I am having right now is that it appears that the socket is not opening properly. The recv function just returns -1 (which indicates a socket error I believe)
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <windows.h>
#define BUFFERSIZE 4096
char *readsite(const char *url, const char *ip, const int port)
{
char *req, *ret, *tmp, tmpbuff[256];
int c, i, q;
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in sa = { 0 };
sa.sin_port = htons(port);
sa.sin_addr.s_addr = inet_addr(ip);
for(i = 0; url[i] != 0x00; i++);
req = malloc((i + 18) * sizeof(char));
if(!req) return NULL;
req[0] = 'G';
req[1] = 'E';
req[2] = 'T';
req[3] = ' ';
for(c = 4, q = 0; q <= i; c++, q++) req[c] = url[q];
req[c - 1] = ' ';
req[c + 0] = 'H';
req[c + 1] = 'T';
req[c + 2] = 'T';
req[c + 3] = 'P';
req[c + 4] = '/';
req[c + 5] = '1';
req[c + 6] = '.';
req[c + 7] = '0';
req[c + 8] = '\r';
req[c + 9] = '\n';
req[c + 10] = '\r';
req[c + 11] = '\n';
req[c + 12] = '\0';
connect(sock, (struct sockaddr*)&sa, sizeof(sa));
for(i = 0; req[i] != 0x00; i++);
send(sock, req, i, 0);
printf("%s %s", req, ip);
free(req);
ret = malloc(BUFFERSIZE);
if(!ret) return NULL;
c = 0; // recv value
i = BUFFERSIZE; // buffer size
q = 0; // loaded bytes
while((c = recv(sock, tmpbuff, sizeof(tmpbuff), 0)) > 0)
{
if((q + c + 1) > i)
{
i += BUFFERSIZE;
if(!(tmp = realloc(ret, i))) return NULL;
ret = tmp;
}
}
}
int main(void)
{
readsite("http://www.google.com/", "74.125.226.226", 80);
return 0;
}
Use the error code in errno to figure out what went wrong; perror() is a great function for this, call it after a check for error code != 0. Here is a suggested way of doing so in your code: