我正在研究一个函数,它将(当它完成时)返回一个 html 页面的输出。我刚刚从 StackOverFlow 那里得到了帮助,了解了它是如何recv
工作的,现在我正在完成这个功能。我现在遇到的问题是套接字似乎没有正确打开。该recv
函数只返回-1(我相信这表示套接字错误)
这是代码:
#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;
}