Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sockets problem

Status
Not open for further replies.

chourico

Programmer
Dec 4, 2005
2
PT
hi i´m doing a sockets program that receives a request from a browser
GET /file.jpg HTTP/1.0

and the server answer is of the type:

HTTP/1.0 200 OK
content-lenght:500
and then sends the content of the file.

I have 2 problems:
- the request must be of the type GET /file.jpg HTTP/1.0 followed by 2 characters of end of the line(I dont know how to do this, the \n\n stuff)
- After the server get the request it must send the file-content how can i do this, i even know if my fread() file is correct. The file can be of any type.

here is a piece of my code , if anyone can help
Code:
#define MAX 250
		
int main(int argc, char **argv) {
	int sockfd, new_sockfd;	//sockets identifiers.
	char request[MAX];
	char answer[MAX];
	time_t hours;
	
	char file[20];  //saves file name
	char protocol[8]
	
	FILE *fp;

	
	sockfd = socket(AF_INET,SOCK_STREAM,0);	
	if (sockfd<0) {
		perror("Socket error\n");
		exit(-1);
	}
		
	...	Here i create socket, do bind(), etc. 
		
	while(1) {
		new_sockfd = accept(sockfd, (struct sockaddr *) NULL, NULL);
		 
		read(new_sockfd, request, sizeof(request));
		sscanf(request,"GET %s %s\n\n",file,protocol);
	
  		hours = time(NULL);
			
		fp = fopen(file, "rb");	
		if (fp == NULL) {	
				sprintf(request,"%s 404 Not found\nDate: %sConnection: close\n",protocol,ctime(&hours));
			}
			else {
				int array[max];
				fread(array, sizeof(int), max,fp); 
				sprintf(answer,"%s 200 OK\nDate: %sContent-Lenght: %ld\n",protocol,ctime(&horas));
				fclose(fp);
			}
			
			write(new_sockfd,answer,sizeof(answer));
		
		
		close(new_sockfd);
	}
		
	}
}
 
Well apart from spelling "length" correctly, here are some links to read.

> write(new_sockfd,answer,sizeof(answer));
Since it's an array, you're going to send whatever junk is still in the array, past the end of the first \0 marking the end of your useful string.

> read(new_sockfd, request, sizeof(request));
As well as ignoring the return result, you also ignore the possibility of message fragmentation.

--
 
Your final line needs to be terminated with a carriage-return/line-feed pair twice. So the GET should end with "\r\n\r\n".

Your response back will be terminated with this too.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top