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

相关推荐
Irissgwe1 小时前
5-1、HTTP cookie与session
linux·http·cookie·session
YHL2 小时前
📖前端 HTTP 请求 & LLM 接口开发
前端·https
开发者联盟league2 小时前
container登录失败解决方法。http: server gave HTTP response to HTTPS client
数据库·http·https
小哇6663 小时前
MCP服务 SSE / Streamable HTTP 这两种数据传输机制,怎么用 http 请求查询这个MCP服务支持哪些工具调用, 和怎么调用其中一个工具
网络·网络协议·http
程序员二叉3 小时前
【计算机网络】面试全解|OSI/TCPIP、HTTP全版本、HTTPS、DNS一站式梳理
计算机网络·http·面试
2501_916007474 小时前
不用 Mac 也可以 Windows下管理iOS描述文件的非Xcode完整指南
android·ios·小程序·https·uni-app·iphone·webview
MyFreeIT14 小时前
Let’s Encrypt
https·let’s encrypt
Oo92018 小时前
Prompt 在 NLP 中的应用——从一条 HTTP 请求说起
http
米丘19 小时前
HTTP 3xx 重定向类状态码
http·node.js
代码中介商20 小时前
HTTP 完全指南(一):请求与响应报文结构深度详解
网络·网络协议·http