0

I'm new to socketprogramming and wanted to write a little console app to receive a webpage and just print it out.

This is my code:

#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;
}

It compiles and then when I enter for example www.google.com it crashes and it gives me file of C. I'm looking for the error but in my opinion I'm doing it right...

Can someone help me please?

Kind regards,

4

2 回答 2

0

感谢 Marcus,需要在 recv 之前进行连接。还有一个小错误是我在进行连接之前进行了发送。改变它,一切正常!

谢谢您的帮助。

于 2012-10-06T18:10:30.330 回答
0

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

于 2012-10-06T15:55:57.953 回答