My goal is to read the returned http status code (very first line returned) after the get request. Then if the status code is 200 then print the rest of the message otherwise only print the status code. How can I achieve this?
My current code returns the whole webpage:
main(int argc, char *argv)
struct sockaddr_in server;
struct hostent *server_host;
fprintf(stderr,"Usage: %s <website> \n",argv);
if (server_host == NULL)
herror("While calling gethostbyname()");
csd=socket(PF_INET, SOCK_STREAM, 0);
perror("While calling socket()");
memcpy(&server.sin_addr, server_host->h_addr_list, server_host->h_length);
server.sin_port = htons(80);
t = connect(csd, (struct sockaddr *) &server, server_len);
printf("connected to server\n\n");
sprintf(temp_buffer, "GET / HTTP/1.0\r\n");
sprintf(temp_buffer, "HOST: %s\r\n", argv);
write(csd, req_buffer, strlen(req_buffer));
chars_read = read(csd, receiveBuffer, 10000);
if (chars_read == 0)
fwrite (receiveBuffer, sizeof (receiveBuffer), chars_read, stdout);
csd were a file handle instead of a file descriptor, I'd suggest using
fgets to process the input stream line by line.
But it's not :-)
So you have (at minimum) a couple of options.
First, you could read character by character, adding it to a buffer, then, when you read a newline, pass said buffer to a function to handle the enire line before zeroing out the buffer and continuing.
Or you could read the entire message and post-process it in a similar manner, looking for embedded newlines and passing the relevant portion (ie, a line) to a function for processing.
In terms of your dodgy characters, that could be caused by many things but I'd be looking out for (again, at a minimum):
printfwith an uncontrolled string. The correct way of doing this is
printf("%s", dodgyString)to ensure that any
%characters in the string don't cause problems.
10000as a limit on it. You should really use
BUF_LENas the limit.
fwrite. You should either use a unit size of
1and unit count of
chars_read, or the other way around. Writing
BUF_LEN * chars_readcharacters when you've only read
chars_readis going to cause you problems.