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

相关推荐
专注VB编程开发20年9 小时前
常见 HTTP 方法的成功状态码200,204,202,201
开发语言·网络协议·tcp/ip·http
Running_C16 小时前
常见web攻击类型
前端·http
搬砖天才、19 小时前
SpringGateway网关增加https证书验证
网络协议·http·https
0wioiw01 天前
Flutter基础(前端教程⑦-Http和卡片)
前端·flutter·http
AliciaIr1 天前
揭秘HTTP的“无情”与前端存储的“深情”:从Cookie到IndexedDB,你真的懂了吗?
http
2501_916008891 天前
iOS App抓包工具排查后台唤醒引发请求异常
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915918412 天前
iPhone 抓包工具有哪些?多工具对比分析优缺点
websocket·网络协议·tcp/ip·http·网络安全·https·udp
小何学计算机2 天前
HTTPS工作原理
网络协议·http·https
游戏开发爱好者82 天前
iOS 出海 App 安全加固指南:无源码环境下的 IPA 加固与防破解方法
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915921432 天前
苹果App上架流程:不用Mac也可以上架的方法
websocket·网络协议·tcp/ip·http·网络安全·https·udp