服务器端的程序一般有如下几个过程,首先是bind,然后再是listen,最后是accept。再往后就是客户端与服务器连接后的各种操作了。
相比之下,客户端的程序就比较简单了,只需先获得sock_id,再与对应的sock进行connect,其他如下。
服务器端代码:
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<sys/types.h> 4 #include<sys/socket.h> 5 #include<netinet/in.h> 6 #include<netdb.h> 7 #include<time.h> 8 #include<string.h> 9 #define PORTNUM 15000 10 #define HOSTLEN 256 11 #define oops(msg) {printf("error:%s ",msg);return 1;} 12 int main(int ac,char * av[]){ 13 struct sockaddr_in saddr; 14 struct hostent * hp; 15 char hostname[HOSTLEN]; 16 int sock_id,sock_fd; 17 FILE * sock_fpi,* sock_fpo; 18 FILE * pipe_fp; 19 char dirname[BUFSIZ]; 20 char command[BUFSIZ]; 21 int dirlen,c; 22 sock_id=socket(PF_INET,SOCK_STREAM,0);//set socket 23 if(sock_id==-1) 24 oops("socket"); 25 bzero((void *)&saddr,sizeof(saddr));//empty saddr 26 gethostname(hostname,HOSTLEN); 27 printf("hostname:%s ",hostname); 28 hp=gethostbyname(hostname); 29 bcopy((void *)hp->h_addr,(void *)&saddr.sin_addr,hp->h_length); 30 saddr.sin_port=htons(PORTNUM); 31 saddr.sin_family=AF_INET; 32 if(bind(sock_id,(struct sockaddr *)&saddr,sizeof(saddr))!=0)//bind address 33 oops("bind"); 34 if(listen(sock_id,1)!=0)//listen 35 oops("listen"); 36 while(1){ 37 sock_fd=accept(sock_id,NULL,NULL);//start accept 38 if(sock_fd==-1) 39 oops("accept"); 40 if((sock_fpi=fdopen(sock_fd,"r"))==NULL) 41 oops("fdopen reading"); 42 if(fgets(dirname,BUFSIZ-5,sock_fpi)==NULL) 43 oops("reading dirname"); 44 sanitize(dirname); 45 if((sock_fpo=fdopen(sock_fd,"w"))==NULL) 46 oops("fdopen writing"); 47 sprintf(command,"ls %s",dirname); 48 if((pipe_fp=popen(command,"r"))==NULL) 49 oops("popen"); 50 while((c=getc(pipe_fp))!=EOF) 51 putc(c,sock_fpo); 52 pclose(pipe_fp); 53 pclose(sock_fpo); 54 pclose(sock_fpi); 55 } 56 } 57 sanitize(char * str){ 58 char * src,* dest; 59 for(src=dest=str;*src;src++) 60 if(*src=='/'||isalnum(*str)) 61 *dest++=*src; 62 *dest='