bleedi 3 Junior Poster in Training

EDIT:
I found the solution already. I had to malloc() memory for rec_msg. :)

Hi,

I've got a little problem with my (unix) C program. I'm trying to make a HTTP request to fetch a page from a site. I can resolve the IP, make a socket, connect and send the HTTP request, but then the recv() function returns -1, and errno tells me "Bad value for ai_flags". I have no idea what this is or means, and after googling for a while, I decided it's more efficient to ask it here. :)

So, here's my code. It's a bit messy, and don't even start with all the hideous stuff I've done there, it's just a try-out for a bigger program. :P

#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/types.h>

int main(int argc, char * argv[]) {
    
    if(argc != 2) {
        fprintf(stderr, "Usage: %s address\n", argv[0]);
        return 0;
    }
    
    int s;
    struct addrinfo hints;
    struct addrinfo *p, *res;
    //struct sockaddr_in* addr_in;
    char ipstr[INET6_ADDRSTRLEN];
    
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    
    int e = getaddrinfo(argv[1], "http", &hints, &res);
    if(e != 0) {
        fprintf(stdout, "Error: %s\n", gai_strerror(e));
        return EXIT_FAILURE;
    }
    
    
    
    for(p = res; p != NULL; p = p->ai_next) {
        void *addr;
        struct sockaddr_in *ip = (struct sockaddr_in*)p->ai_addr;
        addr = &(ip->sin_addr);
        inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
        printf("%s --> %s\n", argv[1], ipstr);
    }
    
    
    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    printf("Socket %d ready.\n", s);
    
    
    if(connect(s, res->ai_addr, res->ai_addrlen) == -1) {
        printf("Error while trying to connect.\n");
        return EXIT_FAILURE;
    }
    
    
    
    char *msg = "GET /index.html HTTP/1.1\nHost: www.somepage.net\r\n\r\n";
    int msg_length = strlen(msg);
    int sent_bytes = send(s, msg, msg_length, 0);
    printf("Sent bytes: %d\n", sent_bytes);
    //printf("Hoh: %s", msg);
    
    char *recv_msg;
    int recv_bytes = recv(s, recv_msg, 4096, 0);
    if(recv_bytes == -1) {
        printf("Error -1: %s\n\n", gai_strerror(recv_bytes));
        return 0;
    }
    printf("Recv. bytes: %d\n\n", recv_bytes);
    
    
    freeaddrinfo(res);
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.