C で単純な非並行 Web サーバーを作成しようとしています。Web ブラウザー (localhost:54321) で特定のページを開きます。これにより、C のサーバー プログラムに接続され、ブラウザによって表示される Web ページが返されます。
これが私のコードからの抜粋です:
void reply(char *mesg, int connfd, struct sockaddr_in servaddr, socklen_t len)
{
FILE *fp;
char token1[256];
char *token2;
char response[2048];
char *file;
char *type;
char c_type[50];
char content[2048];
sscanf(mesg, "GET %s HTTP/1.1", file);
if(strcmp(file, "/") == 0){
fp = fopen("index.html", "r");
sprintf(c_type, "text/html");
fgets(content, 256, fp);
while(!feof(fp)){
fgets(token1, 256, fp);
strcat(content, token1);
}
sprintf(response,"HTTP/1.1 200 OK\r\n Content-type:%s\r\n Content-length: %d\r\n\r\n%s", c_type, strlen(content), content);
sendto(connfd,response,strlen(response),0,(const struct sockaddr *)&servaddr,len);
fclose(fp);
}else{
token2 = strsep(&file, "/");
fp = fopen(file, "r");
if(fp == NULL){\
sprintf(c_type, "text/html");
sprintf(content, "<html><body> <h1> ERROR: %s does not exist! </h1> </body></html>", file);
sprintf(response,"HTTP/1.1 200 OK\r\n Content-type:%s\r\n Content-length: %d\r\n\r\n%s", c_type, strlen(content), content);
sendto(connfd,response,strlen(response),0,(const struct sockaddr *)&servaddr,len);
}else{
type = file;
token2 = strsep(&type, ".");
if(strcmp(type, "html") == 0){
sprintf(c_type, "text/html");
}else if(strcmp(type, "css") == 0){
sprintf(c_type, "text/html");
}else{
sprintf(c_type, "image/%s", type);
}
fgets(content, 256, fp);
while(!feof(fp)){
fgets(token1, 256, fp);
strcat(content, token1);
}
sprintf(response,"HTTP/1.1 200 OK\r\n Content-type:%s\r\n Content-length: %d\r\n\r\n%s", c_type, strlen(content), content);
sendto(connfd,response,strlen(response),0,(const struct sockaddr *)&servaddr,len);
}
fclose(fp);
}
実行すると、プログラムでセグメンテーション違反が発生します。fgets()
ファイル内のデータを解析する方法についてアイデア/コメント/提案があれば、それは私の使用によるものだと思います。ありがとうございました。