| 1- I try \r\n before, it didn't work(no answer from server)
that is why I use \n\n.
2-3- I also try before combination with and without
Keep-Alive & Host. But still doesn't work for www.altavista.com
Maybe you didn't see the combination that I tried because of
the bad indentation. Here is the code again with indentation
and without error handling case so it is easier to read.
Execution line: ./testing www.yahoo.com
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // htons(), htonl()
#include <string.h>
#include <iostream.h>
int main(int argc, char *argv[])
{
// Socket connection
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
struct hostent *host;
host = gethostbyname(argv[1]);
if(host == NULL) // Unresolve host name.
{
fprintf(stderr, "gethostbename() failed");
exit(1);
}
else
{
// Copy host address to sock.
memcpy((caddr_t)& sin.sin_addr, host->h_addr,
host->h_length);
}
// IPPROTO_TCP == 0.
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(connect(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0)
{
perror("connect() failed!");
close(sock);
exit(1);
}
char szbuffer[1445];
// Prepare the request string.
strcpy(szbuffer, "GET / HTTP/1.1\nHost: www.yahoo.com\n\n ");
// Send request.
if(send(sock, szbuffer, strlen(szbuffer), MSG_OOB) < 0)
{
perror("send() failed!");
exit(1);
}
// Clear szbuffer.
memset(szbuffer, '\0', sizeof(szbuffer));
// Open file to be written on.
FILE *stream;
if((stream = fopen("t.htm", "wb")) == NULL)
perror("Can not write file!");
int numBytesRecv=0, i=0;
while( (i = recv(sock, szbuffer, sizeof(szbuffer), 0)) > 0 )
{
numBytesRecv += fwrite(szbuffer, sizeof(char), i, stream);
memset(szbuffer, '\0', sizeof(szbuffer));
}
printf("Number of Bytes received: %i\n", numBytesRecv);
return 0;
}
| |