Hi I am working on a program that will connect to a server that I input from the command line and make a request for the HTTP response. I am currently using www.yahoo.com as a test site for my project. The problem I am running into is that in the recv() function I am receiving the error Bad value for the ai_flags. I also have done some more error checking and have found that my program is using a datagram connection rather than a socket_stream and I'm not sure why. If anyone could help me figure out why either of these things are happening I would greatly appreciate it.
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int sockfd;
int status;
struct addrinfo hints, *res;
struct addrinfo *servinfo;
if (argc != 2) {
fprintf(stderr,"usage: webclient hostname\n");
return 1;
}
memset(&hints, 0, sizeof(hints)); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_protocol = 6;
// get ready to connect
if ((status = getaddrinfo(argv[1], "http", &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
fprintf(stderr, "socket() error: %s %d\n", gai_strerror(sockfd), errno);
return -1;
}
if((status = connect(sockfd, res->ai_addr, res->ai_addrlen)) < 0)
{
fprintf(stderr, "connect() error: %s\n", gai_strerror(status));
return -1;
}
printf ("%s \n", "Success!!!!!");
//Start Sending Part of Code
char *msg = "GET /index.html HTTP/1.1\r\nHOST: www.yahoo.com\r\n\r\n";
int len, bytes_sent;
len = strlen(msg);
bytes_sent = send(sockfd, msg, len, 0);
if(bytes_sent == -1)
{
printf("%s \n", "Error on send() function");
return 5;
}
printf("length: %d, bytes_sent: %d \n", len, bytes_sent);
//End of Sending Part of Code
//Start of the recieving
char *buf; //buffer to hold the recieved message
int bytes_recieved, rec_len;
rec_len = 4096; //Not sure what value to set this as???
bytes_recieved = recv(sockfd, buf, rec_len, 0);
if(bytes_recieved == -1)
{
fprintf(stderr, "recv() error: %s\n res->ai_socktype: %d\n", gai_strerror(bytes_recieved), res->ai_family);
return 6;
}
printf("length: %d, bytes_recieved: %d \n", rec_len, bytes_recieved);
//End of recieving part of code
close(sockfd); //close socket
return 0;
}
Comment