服务器端的程序一般有如下几个过程,首先是bind,然后再是listen,最后是accept。再往后就是客户端与服务器连接后的各种操作了。
相比之下,客户端的程序就比较简单了,只需先获得sock_id,再与对应的sock进行connect,其他如下。
服务器端代码:
1 #include2 #include 3 #include 4 #include 5 #include in.h> 6 #include 7 #include 8 #include<string.h> 9 #define PORTNUM 15000 10 #define HOSTLEN 256 11 #define oops(msg) {printf("error:%s\n",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\n",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='\0'; 63 }
客户端代码:
1 #include2 #include 3 #include 4 #include in.h> 5 #include 6 #define oops(msg) {printf("error:%s\n",msg);return 1;} 7 #define PORTNUM 15000 8 main(int ac,char * av[]){ 9 struct sockaddr_in servadd; 10 struct hostent * hp; 11 int sock_id,sock_fd; 12 char message[BUFSIZ]; 13 char buffer[BUFSIZ]; 14 int messlen,n_read; 15 sock_id=socket(PF_INET,SOCK_STREAM,0);//attention:PF_INT NOT AF_INT 16 if(sock_id==-1) 17 oops("socket"); 18 bzero(&servadd,sizeof(servadd)); 19 hp=gethostbyname(av[1]); 20 if(hp==NULL) 21 oops(av[1]); 22 bcopy(hp->h_addr,(struct sockaddr *)&servadd.sin_addr,hp->h_length); 23 servadd.sin_port=htons(PORTNUM); 24 servadd.sin_family=AF_INET; 25 if(connect(sock_id,(struct sockaddr *)&servadd,sizeof(servadd))!=0)//connect 26 oops("connect"); 27 if(write(sock_id,av[2],strlen(av[2]))==-1) 28 oops("write"); 29 if(write(sock_id,"\n",1)==-1) 30 oops("write"); 31 while((n_read=read(sock_id,buffer,BUFSIZ))>0) 32 if(write(1,buffer,n_read)==-1) 33 oops("write"); 34 close(sock_id); 35 }
调用如下:
服务器启动:./rlsd&
客户端访问:./rls jsonzhang-Vostro-23-3340 ~/桌面/workplace/