Skip to content

Instantly share code, notes, and snippets.

@vtols
Created February 25, 2015 20:51
Show Gist options
  • Save vtols/648594882d1dd59bee2e to your computer and use it in GitHub Desktop.
Save vtols/648594882d1dd59bee2e to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <poll.h>
#define DEFAULT_PORT 8080
#define DEFAULT_IP htonl(INADDR_ANY)
int get_port()
{
int port;
char *s_port = getenv("PORT");
if (!s_port)
return DEFAULT_PORT;
sscanf(s_port, "%d", &port);
return port;
}
int get_ip()
{
char *s_ip = getenv("IP");
if (!s_ip)
return DEFAULT_IP;
return inet_addr(s_ip);
}
char head[] =
"HTTP/1.0 200 OK\r\n"
"Server: Leus\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 71\r\n"
"Connection: Keep-Alive\r\n"
"\r\n",
start[] =
"<head></head>"
"<body>",
end[] =
"<br>"
"<a href=\"/\">Regen</a></body>";
char *rand_s()
{
int i, z;
char buf[21];
for (i = 0; i < 20; i++) {
z = rand() % 62;
if (z < 26)
buf[i] = z + 'a';
else if (z < 52)
buf[i] = z + 'A' - 26;
else
buf[i] = z + '0' - 52;
}
buf[20] = 0;
return strdup(buf);
}
void *client(void *cl)
{
int cl_socket = *(int *) cl;
struct pollfd pfd;
pfd.fd = cl_socket;
pfd.events = POLLIN | POLLRDHUP;
puts("Recieve/Send");
char buf[1000], *rs;
for (;;) {
poll(&pfd, 1, -1);
/* Check events right in this order
* because POLLHUP event always
* goes with POLLIN
*/
if (pfd.revents & POLLRDHUP)
break;
else if (pfd.revents & POLLIN) {
read(cl_socket, buf, 1000);
rs = rand_s();
sprintf(buf, "%s%s%s%s", head, start, rs, end);
free(rs);
write(cl_socket, buf, strlen(buf));
}
}
puts("End R/S");
/* Without keepalive we would write above out of loop
* and after add
*
* shutdown(cl_socket, SHUT_RDWR);
*/
close(cl_socket);
return NULL;
}
int main()
{
int serv_socket, cl_socket;
pthread_t *th;
struct sockaddr_in serv_addr;
int optval = 1;
srand(time(NULL));
serv_socket = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = get_ip();
serv_addr.sin_port = htons(get_port());
setsockopt(serv_socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
bind(serv_socket, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
listen(serv_socket, 10);
while (1) {
cl_socket = accept(serv_socket, (struct sockaddr*)NULL, NULL);
th = malloc(sizeof(pthread_t));
pthread_create(th, NULL, client, &cl_socket);
free(th);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment