加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
tcp_client.c 3.09 KB
一键复制 编辑 原始数据 按行查看 历史
胡宇彪 提交于 2019-09-04 19:00 . 文件传输实现的基本代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"client_cmd.h"
#include"tcp_client.h"
//tcp传输
int tcp_client_put(int sockfd,SI addr)
{
printf("请输入要上传的文件\n");
char str[256] = {};
scanf("%s",str);
//开始通信
char buf[1024] = {};
strcpy(buf,str);
FILE* fd = fopen(buf,"rb");
if(NULL == fd)
{
strcpy(buf,"quit");
send(sockfd,buf,strlen(buf)+1,0);
printf("文件不存在\n");
return ERROR;
}
//发送文件名
send(sockfd,buf,strlen(buf)+1,0);
recv(sockfd,buf,sizeof(buf),0);
//校验时间
struct stat state = {};
stat(str,&state);
sprintf(buf,"%lu",state.st_atime);
send(sockfd,buf,strlen(buf)+1,0);
//接收命令
recv(sockfd,buf,sizeof(buf),0);
printf("%s\n",buf);
if(!strcmp("exis",buf))
{
send(sockfd,buf,strlen(buf)+1,0);
//接收从第几个字节开始
recv(sockfd,buf,sizeof(buf),0);
long ret = 0;
sscanf(buf,"%ld",&ret);
fseek(fd,ret,SEEK_CUR);
}
printf("开始写入内容\n");
while(1)
{
char ch[1024] = {};
int ret = fread(ch,1,10,fd);
send(sockfd,ch,strlen(ch)+1,0);
recv(sockfd,ch,sizeof(ch),0);
chmod(str,0644);
if(10 > ret)
{
strcpy(ch,"close");
send(sockfd,ch,strlen(ch)+1,0);
uint8_t enc1[16] = {};
uint8_t enc2[16] = {};
getmd5_file(fd,enc1);
recv(sockfd,enc2,sizeof(enc2),0);
if(0 == md5cmp(enc1,enc2))
{
printf("传输完成\n");
}
else
{
printf("传输失败文件有损坏\n");
}
fclose(fd);
return SUCCESS;
}
}
return SUCCESS;
}
//tcp下载
int tcp_client_get(int clifd,SI addr)
{
printf("请输入要下载的文件\n");
char str[256] = {};
scanf("%s",str);
//发送名字
send(clifd,str,strlen(str)+1,0);
//接收文件名
char buf[256] = {};
recv(clifd,buf,sizeof(buf),0);
if(!strcmp(buf,"quit"))
{
printf("文件不存在\n");
return ERROR;
}
//清理缓冲区
send(clifd,buf,strlen(buf)+1,0);
//打开文件
FILE* fd = fopen(str,"rb");
//接收时间
recv(clifd,buf,sizeof(buf),0);
long unsigned int time = 0;
sscanf(buf,"%lu",&time);
struct stat state = {};
stat(str,&state);
//如果文件存在 时间相同
if(fd != NULL && state.st_atime-time < 10)
{
printf("文件重传\n");
strcpy(buf,"exis");
send(clifd,buf,strlen(buf)+1,0);
recv(clifd,buf,sizeof(buf),0);
//告知第几个字节开始
fseek(fd,0,SEEK_END);
long ret = ftell(fd);
sprintf(buf,"%ld",ret);
send(clifd,buf,strlen(buf)+1,0);
fd = fopen(str,"ab+");
}
else //覆盖
{
printf("传输文件\n");
strcpy(buf,"continue");
send(clifd,buf,strlen(buf)+1,0);
fd = fopen(str,"wb+");
}
while(1)
{
char ch[1024] = {};
recv(clifd,ch,sizeof(ch),0);
if(!strcmp(ch,"close"))
{
uint8_t encrypt[16] = {};
getmd5_file(fd,encrypt);
send(clifd,encrypt,sizeof(encrypt),0);
bzero(ch,sizeof(ch));
recv(clifd,ch,sizeof(ch),0);
puts(ch);
fclose(fd);
break;
}
send(clifd,ch,strlen(ch)+1,0);
int ret = strlen(ch);
fwrite(ch,1,ret,fd);
}
return SUCCESS;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化