diff options
Diffstat (limited to 'q7/server.c')
-rw-r--r-- | q7/server.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/q7/server.c b/q7/server.c new file mode 100644 index 0000000..12df5bb --- /dev/null +++ b/q7/server.c | |||
@@ -0,0 +1,62 @@ | |||
1 | #include <stdio.h> | ||
2 | #include <stdlib.h> | ||
3 | #include <sys/types.h> | ||
4 | #include <sys/socket.h> | ||
5 | #include <netinet/in.h> | ||
6 | #include <unistd.h> | ||
7 | #include <string.h> | ||
8 | #include <arpa/inet.h> | ||
9 | #include <wait.h> | ||
10 | |||
11 | int main(int argc, char *argv[]) { | ||
12 | int sockfd, connfd; | ||
13 | struct sockaddr_in servaddr, cli; | ||
14 | |||
15 | sockfd = socket(AF_INET, SOCK_STREAM, 0); | ||
16 | servaddr.sin_family = AF_INET; | ||
17 | servaddr.sin_addr.s_addr = htonl(INADDR_ANY); | ||
18 | |||
19 | int port = atoi(argv[1]); | ||
20 | servaddr.sin_port = htons(port); | ||
21 | |||
22 | bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); | ||
23 | |||
24 | listen(sockfd, 128); | ||
25 | printf("Server started at %s...\n", inet_ntoa(servaddr.sin_addr)); | ||
26 | fflush(stdout); | ||
27 | |||
28 | while(1) { | ||
29 | socklen_t len = sizeof(cli); | ||
30 | connfd = accept(sockfd, (struct sockaddr *)&cli, &len); | ||
31 | int i = getpeername(connfd, (struct sockaddr*)&cli, &len); | ||
32 | |||
33 | printf("Client connected at port %d\n", htons(cli.sin_port)); | ||
34 | int n; | ||
35 | char buf[100]; | ||
36 | int pid; | ||
37 | |||
38 | if((pid=fork())==0){ | ||
39 | close(sockfd); | ||
40 | while((n = recv(connfd, buf, 100, 0)) > 0) { | ||
41 | printf("Client message: %s\n", buf); | ||
42 | int pipes[2]; | ||
43 | pipe(&pipes[0]); | ||
44 | if ((pid=fork()) == 0) { | ||
45 | dup2(pipes[1], STDOUT_FILENO); | ||
46 | close(pipes[0]); | ||
47 | execl("/bin/sh", "sh", "-c", buf, (char *) NULL); | ||
48 | } else { | ||
49 | close(pipes[1]); | ||
50 | char cmd_output[1024]; | ||
51 | int cmd_size = read(pipes[0], cmd_output, sizeof(cmd_output)); | ||
52 | send(connfd, cmd_output, cmd_size, 0); | ||
53 | wait(NULL); | ||
54 | } | ||
55 | fflush(stdout); | ||
56 | }; | ||
57 | exit(0); | ||
58 | } | ||
59 | close(connfd); | ||
60 | } | ||
61 | return 0; | ||
62 | } | ||