Hey guys,
I'm RAKESH....i need to write a C program to display the pagesource of a webpage.....
I came up with this piece of code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 9999
#define HOST_ADDRESS "74.125.127.100"
#define HOST_PORT 80
int ReadData(int Sockfd,char *buffer,unsigned int uibuffersize);
int main(int argc,char *argv[])
{
struct sockaddr_in saRemoteHost;
int Sockfd=-1;
char buffer[BUFFER_SIZE];
int DataRecieved=0;
const char Request[]= "GET / HTTP/1.1\r\n\r\n";
do
{
Sockfd=socket(AF_INET,SOCK_STREAM,0);
if(Sockfd==-1)
{
puts("error creating socket");
break;
}
memset(&saRemoteHost, 0, sizeof(saRemoteHost));
memset(buffer, 0, sizeof(buffer));
saRemoteHost.sin_family = AF_INET;
saRemoteHost.sin_port = htons(HOST_PORT);
saRemoteHost.sin_addr.s_addr = inet_addr(HOST_ADDRESS);
if(saRemoteHost.sin_addr.s_addr==-1)
{
puts("Invalid address");
break;
}
if(connect(Sockfd, (struct sockaddr *)&saRemoteHost, sizeof(saRemoteHost))==-1)
{
puts("not able to connect");
break;
}
if (write(Sockfd, Request, sizeof(Request)) == -1)
{
puts("Request failed");
break;
}
DataRecieved=ReadData(Sockfd, buffer, BUFFER_SIZE);
if(DataRecieved==-1)
{
puts("Read error");
break;
}
printf("Recieved: %d bytes \n",DataRecieved);
printf("\n %s \n",buffer);
}while(0);
if(Sockfd!= -1)
{
close(Sockfd);
}
return EXIT_SUCCESS;
}
int ReadData(int Sockfd, char *buffer,unsigned int uibuffersize)
{
int ReadResult=-1;
int DataRecieved=0;
ReadResult=read(Sockfd,buffer,uibuffersize);
while(ReadResult!=0)
{
if(ReadResult==-1)
{
puts("read error");
break;
}
DataRecieved+=ReadResult;
ReadResult = read(Sockfd, buffer+DataRecieved, uibuffersize-DataRecieved);
}
if(ReadResult!=0)
{
DataRecieved=-1;
}
return DataRecieved;
}
This is just a sort of crude coding of what i've been assigned...I need some refinement.......can someone guide me through the refinement process.....
also i get the error
BAD request when i try to access certain webpages.....
again any help???