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

相关推荐
Lsetea9 小时前
Java 请求 HTTPS 报 PKIX path building failed:从证书链到 truststore 的完整排查
java·https·ssl证书·keytool·truststore
Lhappy嘻嘻10 小时前
网络(六)|应用层 HTTP&HTTPS:URL、请求响应、Cookie 与证书
网络·http·https
Lsetea12 小时前
Nginx HTTPS证书域名不匹配:用SAN与SNI定位 ERR_CERT_COMMON_NAME_INVALID
nginx·https·ssl证书·openssl·tls
ControlRookie1 天前
第23篇_源码加更 05|HTTP Server、连接实例和诊断数据
http·codesys·plc通信·开源源码
企业数字化笔记1 天前
AI写的网站一直自动跳转怎么办?301、302和HTTPS重定向排查
网络协议·http·https
那年窗外下的雪.1 天前
AIDC 学习日志|第 24 天|设备输出反推与 MAC Flapping 定位
网络协议·学习·tcp/ip·http·macos·tcpdump
sugar__salt2 天前
大模型流式输出完全指南(上):从 HTTP 长连接到手写 SSE
网络·网络协议·http
2501_915106322 天前
苹果App Store上架费用及流程全面解析
android·ios·小程序·https·uni-app·iphone·webview
2601_962885722 天前
不用 SDK 也能取 A 股数据:AlphaFeed REST API用 cURL/HTTP 直连教程
网络·网络协议·http
为思念酝酿的痛2 天前
应用层协议HTTPS
网络·网络协议·http·https