Last active
December 27, 2015 08:39
-
-
Save haileys/7298087 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <arpa/inet.h> | |
#include <errno.h> | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
const char* response = | |
"HTTP/1.1 797 This is the last page of the Internet. Go back\r\n" | |
"Server: lol\r\n" | |
"Connection: close\r\n" | |
"Content-Type: text/html\r\n" | |
"\r\n" | |
"<h1>this is the last page of the internet</h1>\r\n" | |
"<i>yada yada yada</i>\r\n"; | |
int | |
create_server() | |
{ | |
int servfd, one = 1; | |
struct sockaddr_in addr = { | |
.sin_family = AF_INET, | |
.sin_addr = INADDR_ANY, | |
.sin_port = htons(797) | |
}; | |
if((servfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { | |
perror("socket"); | |
exit(1); | |
} | |
if(setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) { | |
perror("setsockopt"); | |
exit(1); | |
} | |
if(bind(servfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { | |
perror("bind"); | |
exit(1); | |
} | |
if(listen(servfd, 32) < 0) { | |
perror("listen"); | |
} | |
return servfd; | |
} | |
void | |
handle_client(long fd) | |
{ | |
size_t offset = 0; | |
size_t len = strlen(response); | |
while(offset < len) { | |
ssize_t sent = send(fd, response + offset, len - offset, 0); | |
if(sent <= 0) { | |
if(errno == EINTR) { | |
continue; | |
} else { | |
break; | |
} | |
} | |
offset += sent; | |
} | |
shutdown(fd, SHUT_RDWR); | |
close(fd); | |
} | |
int | |
main() | |
{ | |
int servfd = create_server(); | |
while(1) { | |
pthread_t thr; | |
struct sockaddr_in client_addr; | |
socklen_t client_addr_len = sizeof(client_addr); | |
long sock = accept(servfd, (struct sockaddr*)&client_addr, &client_addr_len); | |
if(sock < 0) { | |
continue; | |
} | |
pthread_create(&thr, NULL, (void*(*)(void*))handle_client, (void*)sock); | |
pthread_detach(thr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment