I am coding a web server on C. I am able to view HTML and txt files however I am unable to view image files.
All I get is a error "The image “http://localhost:8080/images/image.jpg” cannot be displayed because it contains errors."
char response[200000];
int main()
{
int client_fd;
char ch, text[256];
char buf[4096];
char method[4096];
char url[4096];
char protocol[4096];
ssize_t bytes_read;
FILE *f;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1)
{
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
bytes_read = read(client_fd, buf, sizeof(buf) - 1);
buf[bytes_read] = '\0';
sscanf (buf, "%s %s %s", method, url, protocol);
if (client_fd == -1)
{
perror("Can't accept");
}
if(strstr(method, "GET") != NULL)
{
f = fopen(url+1, "r");
if(f != NULL)
{
strncat(response, "HTTP/1.1 200 OK\r\n", 20);
if(strstr(url, ".html") || strstr(url, ".htm"))
{
strncat(response, "Content-Type: text/html\r\n\r\n", 30);
}
else if(strstr(url, ".txt"))
{
strncat(response, "Content-Type: text/plain\r\n\r\n", 30);
}
else if(strstr(url, ".jpg") || strstr(url, ".jpeg"))
{
strncat(response, "Content-Type: image/jpeg\r\n\r\n", 30);
}
fseek(f, 0, SEEK_END);
one = ftell(f);
rewind(f);
while(fgets(text, 80, f) != NULL)
{
strncat(response, text, strlen(text));
}
write(client_fd, response, strlen(response)); /*-1:'\0'*/
fclose(f);
}
else
{
write(client_fd, not_found_response, strlen(not_found_response)); /*-1:'\0'*/
}
}
else
{
write(client_fd, bad_request_response, strlen(bad_request_response)); /*-1:'\0'*/
}
close(client_fd);
}
Aucun commentaire:
Enregistrer un commentaire