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

相关推荐
古译汉书2 天前
【IoT死磕系列】Day 7:只传8字节怎么控机械臂?学习工业控制 CANopen 的“对象字典”(附企业级源码)
数据结构·stm32·物联网·http
赤月奇2 天前
https改为http
数据挖掘·https·ssl
21号 12 天前
Http粘包问题回顾
网络·网络协议·http
A懿轩A2 天前
【SpringBoot 快速开发】面向后端开发的 HTTP 协议详解:请求报文、响应码与常见设计规范
spring boot·http·设计规范
吧啦蹦吧2 天前
http-SNI
网络·网络协议·http
~kiss~3 天前
HTTP 429
网络·网络协议·http
Olive3 天前
深入理解 HTTP 请求重试:不只是指数退避那么简单
http
AI-小柒3 天前
Seedance 2.0(即梦 2.0)深度解析:AI 视频进入「导演级」可控时代
大数据·人工智能·网络协议·tcp/ip·http·音视频
弹简特3 天前
【JavaEE10-后端部分】SpringMVC05-综合案例1-从加法计算器看前后端交互:接口文档与HTTP通信详解
java·spring boot·spring·http
弹简特3 天前
【JavaEE12-后端部分】SpringMVC07-综合案例3-从留言板看前后端交互:接口文档与HTTP通信详解
spring boot·网络协议·spring·http·java-ee·交互