服务器端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#define errmes(mes) do{perror(mes);exit(1);}while(0)
#define N 128
int do_list(int acceptfd)
{
DIR *dir;
struct dirent *dirp;
char buf[N] = {};
if((dir = opendir(".")) == NULL)
{
errmes("fail to opendir");
}
while((dirp = readdir(dir)) != NULL) //让dirp指向读到的目录文件
{
if(dirp->d_name[0] == '.') //去掉隐藏文件
{
continue;
}
strcpy(buf, dirp->d_name); //将目录结构体名字放入buf
if(send(acceptfd, buf, N, 0) < 0)
{
errmes("fail to send");
}
usleep(20); //避免粘包
}
printf("目录文件已发送完毕\n");
close(acceptfd);
return 0;
}
int main(int argc, const char *argv[])
{
int sockfd, acceptfd;
struct sockaddr_in serveraddr, clientaddr;
socklen_t clientlen = sizeof(clientaddr);
char buf[N] = {};
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
errmes("fail to socket");
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port =htons(atoi(argv[2]));
if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
{
errmes("fail to bind");
}
if(listen(sockfd, 10) < 0)
{
errmes("fail to listen");
}
while(1)
{
if((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientlen)) < 0)
{
errmes("fail to accept");
}
if(recv(acceptfd, buf, N, 0) < 0)
{
errmes("fail to recv");
}
switch (buf[0])
{
case 'L':
do_list(acceptfd);
break;
default:
printf("输入错素\n");
break;
}
}
return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#define errmes(mes) do{perror(mes);exit(1);}while(0)
#define N 128
int do_list(struct sockaddr_in serveraddr)
{
int sockfd;
char buf[N] = {};
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
errmes("fail to socket");
}
if(connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)))
{
errmes("fail to connect");
}
strcpy(buf, "L");
if(send(sockfd, buf, N, 0) < 0)
{
errmes("fail to send");
}
while(recv(sockfd, buf, N, 0) > 0)
{
printf("%s\n",buf);
usleep(15); //防止粘包
}
printf("目录文件已接收完毕\n");
close(sockfd);
return 0;
}
int main(int argc, const char *argv[])
{
struct sockaddr_in serveraddr;
char buf[N] = {};
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port =htons(atoi(argv[2]));
fgets(buf, N, stdin);
buf[strlen(buf) - 1] = '\0'; //由于fgets函数会将终端输入结束符“\n”也当做字符读入到数组中去,
//所以要将数组最后一个元素“\n”替换成字符串结束符"\0",
if(strncmp(buf, "list", 4) == 0)
{
do_list(serveraddr);
}
return 0;
}