【问题标题】:Return 404error.html page in C web server在 C Web 服务器中返回 404error.html 页面
【发布时间】:2018-06-01 19:07:10
【问题描述】:

我用C编程语言编写了一个Web服务器,并根据URL中提供的请求,Web服务器完全成功地检索了相关网页!以下是处理URL请求的部分代码!

if ( strncmp(reqline[1], "/\0", 2)==0 ) 
    reqline[1] = "/index.html";
    //If no file is specified, index.html will be opened by default  

strcpy(path, ROOT); 
strcpy(&path[strlen(ROOT)], reqline[1]); 
printf("file: %s\n", path); 

if ( (fd=open(path, O_RDONLY))!=-1 )    //If a html file is found
{
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
}
else { //If html file not found
    write (clients[n], "File not found", 15);      
}

当用户提供一个不存在的 html 文件的 URL 而不是文本“文件不找到”当前显示的!

【问题讨论】:

  • 为什么它与你为index.html做的方式不同?
  • 有什么关系?您想读取文件并将其发送给客户端。你的代码中已经有了这个序列。
  • 那么你需要了解为什么它不起作用。
  • 真的是你的代码吗?
  • 我很难相信你写了这段代码,但不知道如何返回 404 页面。似乎不是您编写代码,现在要求您为其添加更多功能。

标签: html c error-handling webserver webpage


【解决方案1】:

我无法编译或运行不完整的代码,但如果找不到请求的文件,“猜测”将是发送错误通知文件。 “404error.html”文件必须存在于可用路径中。

if ( (fd=open(path, O_RDONLY))!=-1 ) {                  // If the file is found
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
    close(fd);                                          // add this
}
else if ( (fd=open("404error.html", O_RDONLY))!=-1 ) {  // Send the error file
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
    close(fd);                                          // add this
}
else {
    write (clients[n], "File not found", 15);           // tough luck, back to to you
}

我不知道clients[n] 是什么,但我相信你知道。

通过不重复传输代码,源代码可能会更有效,但我把它留给你。这个答案是一个想法。

【讨论】:

    【解决方案2】:

    但我不知道writesend 在你的实现中做了什么,但应该始终遵守HTTP,

    响应 = 状态行 *(( 通用标题 |响应头 |实体头)CRLF) CRLF [消息正文]

    来自https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html 的状态代码。这是一个很有前途的 C 编码模型,http://tinyhttpd.sourceforge.net/。具体来说,一般来说,您的 http 响应有什么问题,正如我所见,

    if ( (fd=open(path, O_RDONLY))!=-1 )    //If a html file is found
    {
        send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    }
    else { //If html file not found
        send(clients[n], "HTTP/1.0 404 Not Found\n\n", 20, 0);
        fd = fd_404; // assumes fd_404 is always open
    }
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
    // rewind or close the file . . .
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多