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

相关推荐
冰暮流星12 小时前
flask之http请求方法
网络·网络协议·http
AlfredZhao1 天前
Linux 主机防火墙如何同时开启 80 和 443?
http·https·firewall
从零开始的代码生活_1 天前
NAT、代理服务与内网穿透详解
linux·服务器·网络·c++·http·智能路由器
折哥的程序人生 · 物流技术专研2 天前
Java面试通关⑦:JavaWeb网络核心全集
网络协议·http·javaweb·校招·前后端交互·java面试·社招
小蜗牛的路2 天前
使用OpenSSL生成本地证书https+nginx
网络协议·nginx·https
网络攻城狮_2 天前
网络协议大全
运维·网络·网络协议·http
中云DDoS CC防护蔡蔡2 天前
短信验证码被攻击怎么办
运维·经验分享·http·网络安全·微信
pW3g3lLuu2 天前
.NET 高级开发 | http 接口对接和客户端开发技巧
网络协议·http·.net
山海云端有限公司3 天前
全平台视频元数据解析 API:从原理到 Python 实战调用
python·http·api·元数据·视频解析·apizero
墨香幽梦客3 天前
数据安全三板斧:Https/SSL加密+PCI-DSS合规+HIPAA医疗数据防护
网络协议·https·ssl