TCP协议下的文件传输
此程序是要实现linux下对文件的传输(上传,下载);包括对于Socket套接字的运用,对于目录的操作,对于文件的操作。
成品演示:
运行时带上俩个参数,ip以及端口;
输入 list :显示某个目录下的全部文件列表;
输入get 文件名 :下载文件;
输入put 文件名 :上传;
输入quit或者exit:退出;
程序流程框架图
1,服务器端:

2,客户端:

注意事项:
本代码按照封装思想,使主函数变得简洁,容易理解和编写;
服务器
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define N 128
// ./a.out 192.168.1.57 8000
// argv[0] argv[1] aegv[2]
int process_list(int newsockfd,char *buf)
{
DIR * dirp;
int ret;
struct dirent * direntp;
dirp = opendir("./");
if(dirp == NULL)
{
perror("opendir");
exit(-1);
}
while( (direntp = readdir(dirp)) != NULL)
{
if(strncmp(direntp->d_name,".",1) == 0 ) continue;
strcpy(buf,direntp->d_name);
ret = write(newsockfd,buf,N);
if(ret < 0)
{
perror("write");
exit(-1);
}
}
close(newsockfd);
return 0;
}
int proc

该博客介绍了如何使用TCP协议在Linux环境中实现文件的上传和下载功能。程序通过Socket套接字操作目录和文件,用户通过指定IP和端口交互,执行list显示文件列表,get下载文件,put上传文件,quit或exit退出程序。整个流程遵循封装原则,使得代码结构清晰。
最低0.47元/天 解锁文章
382

被折叠的 条评论
为什么被折叠?



