c - 接收网站的简单套接字程序(断言错误)

标签 c sockets network-programming

我是套接字编程的新手,想编写一个小控制台应用程序来接收网页并将其打印出来。

这是我的代码:

#include <stdio.h>
#include <winsock2.h>
#include <winsock.h>
#include <Ws2tcpip.h>

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

#define BUFFERSIZE 5000

int main()
{
    WSADATA wsaData; 
    char buffer[BUFFERSIZE];
    char *getMsg = {"GET / HTTP/1.0\nUser-Agent: HTTPTool/1.0\n\n"};
    char * url = (char*)malloc(BUFFERSIZE);
    int socket_fd = 0;
    int receivingContent = 1; 
    int errorValue;
    int numbytes;
    struct addrinfo hints;
    struct addrinfo *servinfo, *p;  
    socklen_t addr_size;

    if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0) 
    {
        fprintf(stderr, "WSAStartup failed.\n");
        exit(1);
    }

    memset(&hints, 0, sizeof(hints));   // empty struct
    hints.ai_family = AF_UNSPEC;        // IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM;    // using TCP

    printf("Give a website like for example: www.google.com \n");
    scanf("%s",url);

    //Error testing
    if ((errorValue = getaddrinfo(url, "80", &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(errorValue));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((socket_fd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) {
            perror("Failed to create socket");
            continue;
        }
        break;
    }

    //sending the http get message to the server
    send(socket_fd, getMsg, strlen(getMsg), 0);

    //While the full content isn't downloaded keep receiving
    while(receivingContent)
    {
        numbytes = recv(socket_fd, buffer,BUFFERSIZE , 0);
        if(numbytes > 0)
        {
            buffer[numbytes]='\0';
            printf("%s", buffer);
        }
        else
            receivingContent = 0; //stop receiving
    }

    free(url);
    free(getMsg);
    freeaddrinfo(servinfo);
    closesocket(socket_fd); //close the socket
    WSACleanup();
    return 0;
}

它编译,然后当我输入例如 www.google.com 时,它崩溃并给我 C 文件。我正在寻找错误,但在我看来我做得对......

有人可以帮我吗?

亲切的问候,

最佳答案

我在你的程序中没有找到connect。您可能需要在执行 recv 之前执行 connect

关于c - 接收网站的简单套接字程序(断言错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761214/

相关文章:

c - 如何在 C 中声明大型二维字符数组?

android - C、Android NDK : import own input. h 版本包含缺失声明

c - 你如何找到图中所有可达的节点

android - InetAddress.getLocalHost().getHostAddress() 在 Android 中返回 127.0.0.1

c - 避免在不使用 O_NONBLOCK 时发送到 block

networking - tcp程序无法监听80端口

c - 64 位机器上的 strtok

c - 第二次运行getchar()到哪里去了

ios - NWConnection 发送多个数据报

java - 在java中,同一个程序可以同时作为服务器和客户端运行吗?