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 这样的请求

相关推荐
左手厨刀右手茼蒿4 小时前
Flutter 组件 http_requests 适配鸿蒙 HarmonyOS 实战:极简网络请求,构建边缘端轻量级 RESTful 通讯架构
网络·flutter·http
斌味代码6 小时前
Nginx 配置实战(2026最新版):反向代理+负载均衡+HTTPS+性能优化一网打尽
nginx·https·负载均衡
WIN-U67 小时前
新版华三H3C交换机配置NTP时钟步骤 示例(命令及WEB配置)
网络协议·tcp/ip·http
nbsaas-boot11 小时前
基于 HTTP 构建 MCP Tools 的完整工程解析
网络·网络协议·http·ai
王码码203511 小时前
Flutter for OpenHarmony:使用 pluto_grid 打造高性能数据网格
flutter·http·华为·架构·harmonyos
先跑起来再说11 小时前
从原理到实践:彻底搞懂Cookie和Session的区别
计算机网络·http·https
兰.lan11 小时前
【黑马ai测试】HTTP协议-抓包工具定位-弱网测试-缺陷介绍
网络·python·网络协议·http
虚拟世界AI16 小时前
网络数据架构:构建高效安全的数据基石
网络协议·tcp/ip·5g·https·信息与通信
必胜刻16 小时前
Gin框架---框架CORS
http·https·gin
Vic101011 天前
Wireshark 解密 HTTPS 流量
测试工具·https·wireshark