How to use C language to implement the simplest HTTP server detail

  • 2020-06-23 01:12:53
  • OfStack

The characteristics of this code


<h1>Hello!</h1>

How does it compile and run?

Compile: gcc -o hello_server hello_server.c

Run: ./hello_server

Request: curl http://localhost:8888/any

The source file hello_server c


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define PORT 8888
#define BUFFER_SIZE 4096
#define RESPONSE_HEADER "HTTP/1.1 200 OK\r\nConnection: close\r\nAccept-Ranges: bytes\r\nContent-Type: text/html\r\n\r\n"
#define RESPONSE_BODY "<h1>Hello!</h1>"

int handle(int conn){
  int len = 0;
  char buffer[BUFFER_SIZE];
  char *pos = buffer;
  bzero(buffer, BUFFER_SIZE);
  len = recv(conn, buffer, BUFFER_SIZE, 0);
  if (len <= 0 ) {
    printf ("recv error");
    return -1;
  } else {
    printf("Debug request:\n--------------\n%s\n\n",buffer);
  }

  send(conn, RESPONSE_HEADER RESPONSE_BODY, sizeof(RESPONSE_HEADER RESPONSE_BODY), 0);
  close(conn);// Close the connection 
}

int main(int argc,char *argv[]){
  int port = PORT;
  struct sockaddr_in client_sockaddr;   
  struct sockaddr_in server_sockaddr;
  int listenfd = socket(AF_INET,SOCK_STREAM,0);
  int opt = 1; 
  int conn;
  socklen_t length = sizeof(struct sockaddr_in);
  setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
  server_sockaddr.sin_family = AF_INET;
  server_sockaddr.sin_port = htons(port);
  server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

  if(bind(listenfd,(struct sockaddr *)&server_sockaddr,sizeof(server_sockaddr))==-1){
    printf("bind error!\n");
    return -1;  
  } 

  if(listen(listenfd, 10) < 0) {
    printf("listen failed!\n");
    return -1;  
  }

  while(1){
    conn = accept(listenfd, (struct sockaddr*)&client_sockaddr, &length);
    if(conn < 0){
      printf("connect error!\n");
      continue;
    }
    if (handle(conn) < 0) {
      printf("connect error!\n");
      close(conn);
      continue;
    } 
  }
  return 0;
}

Afterword.

Why write this blog post?

The reason is that when deploying c++ services using an automated platform in your company, use this simple example to test if the platform has a problem. Commonly known as a trip to the pit.

I also searched many blog posts on the Internet, and found several problems with the code. The first problem was compilation, but the second problem was that some code answers had to have files, which caused some trouble to my test.

So refer to others' examples and write a simple one on your own blog. It will be handy when you go to another automated deployment pit.

conclusion


Related articles: