C语言 获取网页内容

参考来源:https://blog.csdn.net/xiahn1a/article/details/41680959
vc6 上编译通过

#include 
#include 
#pragma comment(lib, "ws2_32.lib")

void ReadPage(char *host, char *fname)
{
    int err;
    WSADATA data;
    struct hostent *h; // 主机名
    struct in_addr ina;
    LPSTR ipstr;
    struct sockaddr_in si;
    int sock;
    char request[1024] = "GET /?st=1 HTTP/1.1\r\nHost:";
    FILE *f = fopen(fname, "w");
	if(f==NULL) return;
	
    err = WSAStartup(MAKEWORD(2, 2), &data);
    if(err) return;

    h = gethostbyname(host); // 获取主机名
    if (h == NULL || h->h_addrtype != AF_INET) return;

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

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

    //发送请求
    strcat(request, host);
    strcat(request, "\r\nConnection:Close\r\n\r\n");
    err = send(sock, request, strlen(request), 0);

    //获取网页内容
    while (err > 0)
    {
        char buf[1024] = {0};
        err = recv(sock, buf, sizeof(buf), 0);
        fprintf(f, "%s", buf);
    }
    fclose(f);
    closesocket(sock);
    WSACleanup();
}

int main()
{
    ReadPage("www.baidu.com", "a.txt");
    return 0;
}

你可能感兴趣的:(Windows编程)