HTTP 服务器 demo

c 复制代码
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
  if (argc != 3)
  {
    printf("usage: ./server ip port\n");
    return 1;
  }

  int fd = socket(AF_INET, SOCK_STREAM, 0);
  if (fd < 0)
  {
    perror("socket");
    return 1;
  }

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr(argv[1]);
  addr.sin_port = htons(atoi(argv[2]));

  int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
  if (ret < 0)
  {
    perror("bind");
    return 1;
  }

  ret = listen(fd, 10);
  if (ret < 0)
  {
    perror("listen");
    return 1;
  }

  for (;;)
  {
    struct sockaddr_in client_addr;
    socklen_t len = sizeof(client_addr);
    int client_fd = accept(fd, (struct sockaddr*)&client_addr, &len);
    if (client_fd < 0)
    {
      perror("accept");
      continue;
    }

    char input_buf[1024 * 10] = {0}; /* 用一个足够大的缓冲区直接把数据读完 */
    ssize_t read_size = read(client_fd, input_buf, sizeof(input_buf) - 1);
    if (read_size < 0)
      return 1;

    printf("[Request]\n%s", input_buf);
    char buf[1024] = {0};
    const char *hello = "<h1>hello world</h1>";
    sprintf(buf, "HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s", strlen(hello), hello);
    write(client_fd, buf, strlen(buf));
  }

  return 0;
}

编译后启动服务,并在浏览器中输入 http://ip:port

注意:

1、此处我使用了 9090 端口号启动 HTTP 服务器,虽然 HTTP 服务器一般使用的是 80 端口,但这只是一个通用习惯,并不是说 HTTP 服务器就不能使用其他端口号

2、可以看到服务器打印出的报文中还有一个 GET /favicon.ico HTTP/1.1 这样的请求

相关推荐
light_in_hand3 小时前
HTTP 协议的基本格式和 fiddler 的用法
网络协议·http·fiddler
hai3152475433 小时前
九章编程法 · HTTP转发代理网关【终极完美版·矩阵步进交换】
人工智能·网络协议·线性代数·http·矩阵·极限编程
Patrick_Wilson6 小时前
从「框架内部报错」到「请求头被网关截断」:一次 Sentry 排障与前端 Cookie 误用复盘
前端·http·浏览器
qiuziqiqi6 小时前
webman的消费脚本进程中http请求的选择
网络·网络协议·http
light_in_hand7 小时前
HTTPS 加密流程总结
网络协议·http·https
之歆7 小时前
Node.js HTTP 模块深度解析与实战指南
网络协议·http·node.js
奥利奥夹心脆芙1 天前
辅助排查 HTTP 接口代码报错,实操完整案例分享
http
吠品1 天前
一次 Nginx 报错 unexpected end of file 的排查记录
网络协议·https·ssl
代码中介商1 天前
TLS握手全解析:从1.2到1.3的加密演进
网络·网络协议·http
yuegu7771 天前
HarmonyOS应用<节气通>开发第25篇:HTTP请求封装
网络协议·http·harmonyos