Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- int main(){
- //open a file to serve
- FILE *html_data; //file pointer to hold the data
- html_data = fopen("index.html", "r");
- //file to open, how to use file. w = write, r = read.
- char response_data[1024]; //string to store the HTML of the file in it.
- fgets(response_data, 1024, html_data); //fgets() allows you to read from the file
- //Where to read the data to, how much data to read, file we're reading from.
- char http_header[2048] = "HTTP/1.1 200 OK \r\n\n"; //response to let client know what happened when resource was requested.
- strcat(http_header, response_data); //combines http_header and response_data into one string
- //create a socket
- int server_socket;
- server_socket = socket(AF_INET, SOCK_STREAM, 0);
- //Domain of Socket (Internet Socket), TCP Socket, Protocol(Already using TCP so put as 0)
- //define the address
- struct sockaddr_in server_address; //declares structure for the address.
- server_address.sin_family = AF_INET; //Sets family of address so knows what type of address it's working with: AF_INET
- 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.
- server_address.sin_addr.s_addr = INADDR_ANY; //Any Address
- bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)); //bind socket to a port
- //Network Socket, Casts our address to the right structure type, size of the address
- listen(server_socket, 5); //Listen for connections on socket
- int client_socket;
- while(1) {
- //infinite while loop to have server continue serving and responding to requests
- client_socket = accept(server_socket, NULL, NULL); //accept connection on the client socket
- //not storing address so NULL
- send(client_socket, http_header, sizeof(http_header), 0); //send data back to client
- //where to send it to, response, send the sizeof http header to the send function.
- close(client_socket);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement