#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SMALL_BUF 100
char response1[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html> <html> <head> <title>My Web Page</title> </head> <body>
<h1>Welcome to My Web Page!</h1> </body> </html>\r\n";
char response2[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html> <html> <head> <title>My Web Page</title> </head> <body>
<h1>Welcome to My Web Page2!</h1> </body> </html>\r\n";
char* content_type(char* file);
int main(int argc, char *argv[])
{
struct sockaddr_in server_addr, client_addr;
socklen_t sin_len = sizeof(client_addr);
int fd_server, fd_client;
char buf[2048];
int on = 1;
char indexhtml[]="index.html";
char queryhtml[]="query.html";
char *get;
char *domain;
char *none;
char *message;
char *state;
fd_server = socket(AF_INET, SOCK_STREAM, 0);
if(fd_server < 0)
{
perror("socket error");
exit(1);
}
setsockopt(fd_server, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(50814);
if (bind(fd_server, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
{
perror("bind error");
close(fd_server);
exit(1);
}
if (listen(fd_server, 10) == -1)
{
perror("listen error");
close(fd_server);
exit(1);
}
while(1)
{
fd_client = accept(fd_server, (struct sockaddr *) &client_addr, &sin_len);
if(fd_client == -1)
{
perror("connection failed\n");
continue;
}
if (fd_client > 0)
{
printf("got client connection\n");
}
strcpy(state,strtok(message," /"));
strcpy(domain,strtok(NULL," /"));
printf("state: %s\n",state);
printf("domain: %s\n",domain);
if(strcmp(state,get)==0)
{
if(strcmp(domain,indexhtml)==0||strcmp(domain,none)==0)
{
write(fd_client,response1, sizeof(response1)-1);
}
else if(strcmp(domain,queryhtml)==0)
{
write(fd_client,response2, sizeof(response2)-1);
}
}
}
return 0;
}
I am trying to create a simple web server in c with Linux that runs with localhost. when I type local address:portnumber I want to show "my webpage!" and when I type local address:portnumber/index.html, i want to show "my webpage!" also, and then when I type local address:portnumber/query.html, I want to show "my webpage2!" Howeverm I am keep facing with segmentation fault... Please help me out.. Thank you all for helping me out!!