1. 完成下载(上交)
![](https://i-blog.csdnimg.cn/blog_migrate/70fd0b141762bda7741078625ee2f5e3.png)
![](https://i-blog.csdnimg.cn/blog_migrate/e85658f88d98e35db13b93981d736edf.png)
#include <myhead.h>
#define PORT 69
#define IP "192.168.115.27"
int do_download(struct sockaddr_in sin,int sfd);
int main(int argc, const char *argv[])
{
//创建报式套节字 socket
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
printf("socket create success sfd=%d\n",sfd);
//填充的地址信息结构体给bing函数绑定
//真实的地址信息结构体根据地址族AF_INET:man 7 ip
struct sockaddr_in sin;
sin.sin_family=AF_INET; //必须填AF_INET
sin.sin_port=htons(PORT); //端口号的网络字节序1024~49151
sin.sin_addr.s_addr=inet_addr(IP);//本机ip,ifconfig
char choose=0;
while(1)
{
system("clear");
printf("-----------------------------------\n");
printf("--------------1.下载---------------\n");
printf("--------------2.上传---------------\n");
printf("--------------3.退出---------------\n");
printf("-----------------------------------\n");
printf("请输入>>>");
scanf("%c",&choose);
while(getchar()!=10);
switch(choose)
{
case '1':
do_download(sin,sfd);
break;
case '2':
//do_upload();
break;
case '3':
goto END;
break;
default:
printf("输入错误,请重新输入\n");
break;
}
printf("输入任意字符清屏>>>");
while(getchar()!=10);
}
END:
//关闭文件名描述符
if(close(sfd)<0)
{
ERR_MSG("close");
return -1;
}
return 0;
}
int do_download(struct sockaddr_in sin,int sfd)
{
//组下载请求包
//发送下载请求
char buf[516]="";
char filename[20]="";
printf("请输入下载的文件名>>>");
scanf("%s",filename);
while(getchar()!=10);
/* unsigned short *ptr1= (unsigned short*)buf;
*ptr1=htons(1);
char *ptr2=buf+2;
strcpy(ptr2,filename);
char *ptr3=ptr2+strlen(filename)+1;
strcpy(ptr3,"octet");
int size=2+strlen(ptr2)+1+strlen(ptr3)+1;
*/
int size=sprintf(buf,"%c%c%s%c%s%c",0,1,filename,0,"octet",0);
if(sendto(sfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto download request success\n");
struct sockaddr_in cin;
socklen_t addelen=sizeof(cin);
int fd;
ssize_t ret,DATA;
char ack1,ack2;
if((fd=open("filename", O_WRONLY|O_CREAT|O_TRUNC, 0664)) == -1)
{
ERR_MSG("open");
return -1;
}
while(1)
{
bzero(buf,sizeof(buf));
//接收数据,接收地址信息
if((ret=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&addelen))<0)
{
ERR_MSG("recvfrom");
return -1;
}
printf("recvfrom success\n");
DATA=ret-4;
if(write(fd,buf+4,DATA)<0)
{
ERR_MSG("write");
return -1;
}
ack1=buf[2];
ack2=buf[3];
sin.sin_port=cin.sin_port;
bzero(buf,sizeof(buf));
//组ACK
//发送ACK
size=sprintf(buf,"%c%c%c%c",0,4,ack1,ack2);
if(sendto(sfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto download request success\n");
//判断数据是否小于512字节,小于下载完成
if(DATA<512)
{
printf("下载完成\n");
break;
}
}
return 0;
}
2. 完成上传(尽力完成)
3. 复习重点,整理成脑图(流程图,重点题型)
![](https://i-blog.csdnimg.cn/blog_migrate/051f54cd9fad9fea82cea28876f7a88a.png)