- /*
- *客户端,执行命令,回传执行结果
- *By rekken
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <errno.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #include <string.h>
- #define SERVERPORT 3490
- #define BACKLOG 10
- #define MAX_CONNECTED_NO 10
- #define MAXDATASIZE 120
- int main()
- {
- //declare the variable to be used
- FILE *pp;; //used for file handle, pp used as buf after doing command
-
- char sendout[65535]; //used for store the data retrived from the file
- struct sockaddr_in server_sockaddr,client_sockaddr; //for create socket
- int sin_size,recvbytes,sendbytes; //recv and send used for recv() and send()
- int sockfd,client_fd; //for socket creation
- char buf[MAXDATASIZE]; //store the file dir from recv()
- char output[MAXDATASIZE];
- //creat socket connection
- if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
- perror("socket");
- exit(1);
- }
- printf("socket success!,sockfd=%d\n",sockfd);
-
- //set relevant parameters in the socketr_in struct
- server_sockaddr.sin_family=AF_INET;
- server_sockaddr.sin_port=htons(SERVERPORT);
- server_sockaddr.sin_addr.s_addr=INADDR_ANY;
- bzero(&(server_sockaddr.sin_zero),8);
-
- //bind the sockfd and port
- if(bind(sockfd,(struct sockaddr *)&server_sockaddr,sizeof(struct sockaddr))==-1){
- perror("bind");
- exit(1);
- }
- printf("bind success!\n");
-
- //begin to listen
- if(listen(sockfd,BACKLOG)==-1){
- perror("listen");
- exit(1);
- }
- printf("listening....\n");
-
- //call the accept(),wait for the peer's connecting
- if((client_fd=accept(sockfd,(struct sockaddr *)&client_sockaddr,&sin_size))==-1){
- perror("accept");
- exit(1);
- }
-
- //receive the data from the peer
- if((recvbytes=recv(client_fd,buf,sizeof(buf),0))==-1){
- perror("recv");
- exit(1);
- }
- //do the received command
-
- if((pp = popen(buf, "r")) == NULL )
- {
- printf("popen error!\n");
- return 0;
- }
- while(fgets(output, 255, pp))
- {
- printf("%s", output);
- if((sendbytes=send(client_fd,output,strlen(output),0))==-1){
- perror("send file");
- exit(1);
- }
- printf("send data length:%d\n",sendbytes);
- }
- pclose(pp);
-
- close(sockfd);
- return 1;
- }
- /*
- *讲命令执行部分封装
- */
- int do_command(int sockfd,char *command,char *output)//sockfd套接字用于结果回传,command为待执行命令,output存放执行结果
- {
- FILE *pp;
- int count_byte=0;
- if((pp = popen(command, "r")) == NULL )
- {
- printf("popen error!\n");
- return 0;
- }
- while(!feof(pp)){//判断文件尾,下两行用于将文件内容保存在output中
- output[count_byte]=fgetc(pp);
- count_byte++;
- }
- if((send(sockfd,output,count_byte,0))==-1){//将执行结果发送回请求端
- perror("send file");
- exit(1);
- }
- pclose(pp);
- return count_byte;//返回值为传送字节数
- }