思维导图
#include<myhead.h>
#define SER_PORT 69
#define SER_IP "192.168.125.180"
int do_download(int cfd,struct sockaddr_in sin)
{
//向服务器发送下载请求
char buf[516]="";
char fileName[40]="";
printf("请输入文件名:");
scanf("%s",fileName);
getchar();
//组装请求数据
short *p1=(short*)buf;
*p1=htons(1);
char *p2=buf+2;
strcpy(p2,fileName);
char *p3=p2+strlen(p2)+1;
strcpy(p3,"octet");
int len=4+strlen(p2)+strlen(p3); //要发送的长度
//向服务器发送请求
if(sendto(cfd,buf,len,0,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("sendto error");
return -1;
}
printf("下载成功\n");
}
int do_upload(int sfd,struct sockaddr_in sin)
{
char fileName[20]="";
printf("请输入要上传的文件名>>>");
fgets(fileName,20,stdin);
fileName[strlen(fileName)-1]=0;
//判断文件是否存在
int fd=open(fileName,O_RDONLY);
if(fd<0)
{
if(errno==ENOENT)
{
printf("文件不存在,请重新输入\n");
return -2;
}
else
{
perror("open error");
return -1;
}
}
//上传请求
char buf[516]="";
int size=sprintf(buf,"%c%c%s%c%s%c",0,2,fileName,0,"octet",0);
if(sendto(sfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
perror("sendto error");
return -1;
}
//循环接收发送的数据包
int recv_len;
unsigned short num=0;
socklen_t addrlen=sizeof(sin);
while(1)
{
bzero(buf,sizeof(buf));
if(recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&addrlen)==-1)
{
perror("recvfrom error");
return -1;
}
if(buf[1]==4)
{
if(num==ntohs(*(unsigned short*)(buf+2)))
{
buf[1]=3;
num++;
*(unsigned short*)(buf+2)=htons(num);
//读取数据
int res=read(fd,buf+4,512);
if(res<0)
{
perror("res error");
return -1;
}
else if(res==0)
{
printf("文件上传成功\n");
break;
}
}
else
{
printf("文件上传失败\n");
break;
}
}
else if(buf[1]==5)
{
printf("----ERROR:%s----\n",buf+4);
break;
}
}
return 0;
}
int main(int argc, const char *argv[])
{
if(argc<2)
{
printf("input error\n");
printf("usage:./a.out ip\n");
return -1;
}
//1、创建套接字
int cfd=socket(AF_INET,SOCK_DGRAM,0);
if(cfd==-1)
{
perror("socket error");
return -1;
}
//2、绑定端口号和IP地址
//3、设置监听
//服务器的地址信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(argv[1]);
//选项清单
int mune=-1;
while(1)
{
system("clear");
printf("菜单选项如下:\n");
printf("\t\t======1、下载=======\n");
printf("\t\t======2、上传=======\n");
printf("\t\t======0、退出=======\n");
printf("请输入功能>>>");
scanf("%d",&mune);
getchar();
switch(mune)
{
case 1:
{
//下载功能
do_download(cfd,sin);
}
break;
case 2:
{
//上传功能
do_upload(cfd,sin);
}
break;
case 0:
goto END;
default:printf("输入有误,请重新输入\n");
}
printf("请输入任意键,按回车清空\n");
while(getchar()!='\n');
}
END:
close(cfd);
return 0;
}