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

相关推荐
熊IT6 小时前
HTTP 代理检测工具:快速检查代理可用性、出口 IP 与延迟
网络协议·tcp/ip·http
何以解忧,唯有..6 小时前
HTTP 与 HTTPS:从明文传输到安全加密的演进
安全·http·https
今儿敲了吗6 小时前
CN——HTTP 工作流程
网络·网络协议·http
虎王物联1 天前
ESP32 HTTP客户端开发实战:TLS加密通信与RESTful API集成方案
http·restful·iphone
小僧景贤1 天前
嵌入式网络协议 | MQTT、CoAP与HTTP协议深度解析(原理、差异、工程选型、代码实操)
mqtt·http·物联网协议·coap·网络协议选型
CDN3601 天前
360CDN发布HTTP/3(QUIC)弱网加速方案:实测首屏提速40%,彻底终结移动端接口超时与频繁断连
网络·网络协议·http
翼龙云_cloud1 天前
阿里云国际版代理商:OSS自定义域名绑定与HTTPS配置排障教程
数据库·阿里云·https·云计算
一条泥憨鱼2 天前
【从0开始学习计算机网络】| DNS -记录类型详解
计算机网络·http·github·域名·dns·记录
游戏开发爱好者82 天前
开心上架是什么,一站式 Apple 开发者工作台总览
android·小程序·https·uni-app·iphone·webview
白嫖一茶2 天前
HTTP 状态码总共分为五大类
http