Created
November 26, 2017 03:12
-
-
Save zhaorui/38c782d2119ffc9975449f1f12b75540 to your computer and use it in GitHub Desktop.
Simple http server written in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<netinet/in.h> | |
#include<stdio.h> | |
#include<stdlib.h> | |
#include<sys/socket.h> | |
#include<sys/stat.h> | |
#include<sys/types.h> | |
#include<unistd.h> | |
int main() { | |
int create_socket, new_socket; | |
socklen_t addrlen; | |
int bufsize = 1024; | |
char *buffer = malloc(bufsize); | |
struct sockaddr_in address; | |
if ((create_socket = socket(AF_INET, SOCK_STREAM, 0)) > 0){ | |
printf("The socket was created\n"); | |
} | |
address.sin_family = AF_INET; | |
address.sin_addr.s_addr = INADDR_ANY; //why not local host? | |
address.sin_port = htons(15000); | |
if (bind(create_socket, (struct sockaddr *) &address, sizeof(address)) == 0){ | |
printf("Binding Socket\n"); | |
} | |
while (1) { | |
if (listen(create_socket, 10) < 0) { | |
perror("server: listen"); | |
exit(1); | |
} | |
if ((new_socket = accept(create_socket, (struct sockaddr *) &address, &addrlen)) < 0) { | |
perror("server: accept"); | |
exit(1); | |
} | |
if (new_socket > 0){ | |
printf("The Client is connected...\n"); | |
} | |
recv(new_socket, buffer, bufsize, 0); | |
printf("%s\n", buffer); | |
write(new_socket, "HTTP/1.1 200 OK\n", 16); | |
write(new_socket, "Content-length: 19\n", 19); | |
write(new_socket, "Content-Type: text/json\n\n", 25); | |
write(new_socket, "{\"ip\": \"127.1.2.3\"}",19); | |
close(new_socket); | |
} | |
close(create_socket); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment