C语言使用socket完成HTTP

以后再追加解释,先贴个代码

#define _CRT_SECURE_NO_WARNINGS
#include<windows.h>
#include<stdio.h>
#include<string.h>
#define BUFSIZE 4096
#pragma comment(lib, "ws2_32.lib")

int ReadPage(char* host, char *url, char *buffer, int length)
{
	WSADATA data;
	//winsock版本2.2
	int err = WSAStartup(MAKEWORD(2, 2), &data);
	if (err)
	{
		return -1;
	}


	//用域名获取对方主机名
	struct hostent *h = gethostbyname(host);
	if (h == NULL)
	{
		return -1;
	}

	//IPV4
	if (h->h_addrtype != AF_INET)
	{
		return -1;
	}

	struct in_addr ina;
	//解析IP
	memmove(&ina, h->h_addr, 4);
	LPSTR ipstr = inet_ntoa(ina);

	//Socket封装
	struct sockaddr_in si;
	si.sin_family = AF_INET;
	si.sin_port = htons(80);
	si.sin_addr.S_un.S_addr = inet_addr(ipstr);
	int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	connect(sock, (SOCKADDR*)&si, sizeof(si));
	if (sock == -1 || sock == -2)
	{
		return -1;
	}

	//发送请求
	char request[1024] = "GET ";
	strcat(request, url);
	strcat(request, " HTTP/1.1\r\nHost:");
	strcat(request, host);
	strcat(request, "\r\nConnection:Close\r\n\r\n");
	int ret = send(sock, request, strlen(request), 0);

	int amount = 0;
	while (ret > 0)
	{
		char buf[BUFSIZE];
		ret = recv(sock, buf, BUFSIZE, 0);
		if (ret + amount > length)
		{
			fprintf(stderr, "Error, Buffer size isn't enough!\n");
			return -1;
		}
		memcpy(buffer + amount, buf, ret);
		amount += ret;
	}

	closesocket(sock);
	WSACleanup();
	return amount;
}

int main()
{
	int buf_size = 1024 * 1024 * 10; //10M
	char *buf = (char *)malloc(buf_size);
	int size = ReadPage("www.baidu.com", "/", buf, buf_size);
	if (size < 0)
	{
		printf("Request Failed!\n");
		return -1;
	}
	FILE *f = fopen("index.txt", "wb");
	fwrite(buf, 1, size, f);
}

说点什么

avatar
  Subscribe  
提醒