Advertisement
Guest User

Http_Server_Socket_Shit

a guest
Dec 13th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #include <sys/socket.h>
  6. #include <sys/types.h>
  7.  
  8. #include <netinet/in.h>
  9.  
  10. int main(){
  11.     //open a file to serve
  12.     FILE *html_data; //file pointer to hold the data
  13.     html_data = fopen("index.html", "r");
  14.               //file to open, how to use file. w = write, r = read.
  15.  
  16.     char response_data[1024]; //string to store the HTML of the file in it.
  17.     fgets(response_data, 1024, html_data); //fgets() allows you to read from the file
  18.           //Where to read the data to, how much data to read, file we're reading from.
  19.  
  20.     char http_header[2048] = "HTTP/1.1 200 OK \r\n\n"; //response to let client know what happened when resource was requested.
  21.     strcat(http_header, response_data); //combines http_header and response_data into one string
  22.  
  23.     //create a socket
  24.     int server_socket;
  25.     server_socket = socket(AF_INET, SOCK_STREAM, 0);
  26.         //Domain of Socket (Internet Socket), TCP Socket, Protocol(Already using TCP so put as 0)
  27.    
  28.     //define the address
  29.     struct sockaddr_in server_address; //declares structure for the address.
  30.     server_address.sin_family = AF_INET; //Sets family of address so knows what type of address it's working with: AF_INET
  31.     server_address.sin_port = htons(8001); //defines port number to connect to. htons() is a conversion function to put the port number in the right network byte over.
  32.     server_address.sin_addr.s_addr = INADDR_ANY; //Any Address
  33.  
  34.     bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)); //bind socket to a port
  35.     //Network Socket, Casts our address to the right structure type, size of the address
  36.  
  37.     listen(server_socket, 5); //Listen for connections on socket
  38.  
  39.     int client_socket;
  40.  
  41.     while(1) {
  42.         //infinite while loop to have server continue serving and responding to requests
  43.         client_socket = accept(server_socket, NULL, NULL); //accept connection on the client socket
  44.                             //not storing address so NULL
  45.         send(client_socket, http_header, sizeof(http_header), 0); //send data back to client
  46.             //where to send it to, response, send the sizeof http header to the send function.
  47.         close(client_socket);
  48.     }
  49.  
  50.     return 0;
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement