i am creating a simple server that does nothing but to give an existing file /home/john/www at port 2222. my www folder has three files: index.html, server.c, client.c.
running the server, my firefox can now request for a page thru:
localhost:2222/server.c
the problem is, instead of showing the contents of server.c on my firefox, the file is downloaded instead. (firefox prompts to view or save the file.) same as with index.html and client.c.
i was able to show the contents of server.c days ago on my browser. but i can no longer remember what changes i made to make the browser behave like that.
here's the code snippet where i am doing my modification:
#define LINE_LEN 128
#define MAX_LEN 1024
...
int process_request(int fd, char *www_path) {
char cmessage[MAX_LEN];
char *r;
int n, read_size;
FILE *file;
char line[LINE_LEN];
struct stat sb;
if((n = read(fd, cmessage, MAX_LEN)) <= 0) {
return 6;
}
cmessage[n] = '\0';
// assume GET method
r = cmessage + 4;
n = 0;
while(r[n] != ' ') {
n++;
}
int len = strlen(www_path);
char req_file[len+n+1];
char temp[n+1];
strncpy(temp, r, n);
temp[n] = '\0';
sprintf(req_file, "%s%s", www_path, temp);
if(stat(req_file, &sb) == -1) {
perror("stat");
return 7;
}
char size[10];
sprintf(size, "%d", sb.st_size);
file = fopen(req_file, "rb");
write(fd, "HTTP/1.1 200 OK\r\nContent-length: ", 33);
write(fd, size, strlen(size));
write(fd, "\r\n\r\n", 4);
while((read_size = fread(line, sizeof(char), LINE_LEN, file)) != 0) {
write(fd, line, read_size);
}
fclose(file);
return 0;
}
or is this just a configuration that can be set in my web browser's setting?
more details:
The socket was created using
socket(AF_INET, SOCK_STREAM, 0);
listen(), bind(), and accept() are successful. select() statement is used to wait for file descriptors that are ready for reading. The file descriptors of clients connected are not closed until the read() to a certain file descriptor returns -1.
You need to give the browser a proper content type as part of your server's response. This might be something you either hardcode, or perhaps derive from the file name. For instance:
Content-Type: text/plain