服务器端的程序一般有如下几个过程,首先是bind,然后再是listen,最后是accept。再往后就是客户端与服务器连接后的各种操作了。
相比之下,客户端的程序就比较简单了,只需先获得sock_id,再与对应的sock进行connect,其他如下。
服务器端代码:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<time.h>
#include<string.h>
#define PORTNUM 15000
#define HOSTLEN 256
#define oops(msg) {printf("error:%s\n",msg);return 1;}
int main(int ac,char * av[]){
struct sockaddr_in saddr;
struct hostent * hp;
char hostname[HOSTLEN];
int sock_id,sock_fd;
FILE * sock_fpi,* sock_fpo;
FILE * pipe_fp;
char dirname[BUFSIZ];
char command[BUFSIZ];
int dirlen,c;
sock_id=socket(PF_INET,SOCK_STREAM,);//set socket
if(sock_id==-)
oops("socket");
bzero((void *)&saddr,sizeof(saddr));//empty saddr
gethostname(hostname,HOSTLEN);
printf("hostname:%s\n",hostname);
hp=gethostbyname(hostname);
bcopy((void *)hp->h_addr,(void *)&saddr.sin_addr,hp->h_length);
saddr.sin_port=htons(PORTNUM);
saddr.sin_family=AF_INET;
if(bind(sock_id,(struct sockaddr *)&saddr,sizeof(saddr))!=)//bind address
oops("bind");
if(listen(sock_id,)!=)//listen
oops("listen");
while(){
sock_fd=accept(sock_id,NULL,NULL);//start accept
if(sock_fd==-)
oops("accept");
if((sock_fpi=fdopen(sock_fd,"r"))==NULL)
oops("fdopen reading");
if(fgets(dirname,BUFSIZ-,sock_fpi)==NULL)
oops("reading dirname");
sanitize(dirname);
if((sock_fpo=fdopen(sock_fd,"w"))==NULL)
oops("fdopen writing");
sprintf(command,"ls %s",dirname);
if((pipe_fp=popen(command,"r"))==NULL)
oops("popen");
while((c=getc(pipe_fp))!=EOF)
putc(c,sock_fpo);
pclose(pipe_fp);
pclose(sock_fpo);
pclose(sock_fpi);
}
}
sanitize(char * str){
char * src,* dest;
for(src=dest=str;*src;src++)
if(*src=='/'||isalnum(*str))
*dest++=*src;
*dest='\0';
}
客户端代码:
#include<stdio.h>
#include<linux/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define oops(msg) {printf("error:%s\n",msg);return 1;}
#define PORTNUM 15000
main(int ac,char * av[]){
struct sockaddr_in servadd;
struct hostent * hp;
int sock_id,sock_fd;
char message[BUFSIZ];
char buffer[BUFSIZ];
int messlen,n_read;
sock_id=socket(PF_INET,SOCK_STREAM,);//attention:PF_INT NOT AF_INT
if(sock_id==-)
oops("socket");
bzero(&servadd,sizeof(servadd));
hp=gethostbyname(av[]);
if(hp==NULL)
oops(av[]);
bcopy(hp->h_addr,(struct sockaddr *)&servadd.sin_addr,hp->h_length);
servadd.sin_port=htons(PORTNUM);
servadd.sin_family=AF_INET;
if(connect(sock_id,(struct sockaddr *)&servadd,sizeof(servadd))!=)//connect
oops("connect");
if(write(sock_id,av[],strlen(av[]))==-)
oops("write");
if(write(sock_id,"\n",)==-)
oops("write");
while((n_read=read(sock_id,buffer,BUFSIZ))>)
if(write(,buffer,n_read)==-)
oops("write");
close(sock_id);
}
调用如下:
服务器启动:./rlsd&
客户端访问:./rls jsonzhang-Vostro-23-3340 ~/桌面/workplace/