1、UDP下载
#include<myhead.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__); \
perror(msg);\
}while(0)
#define SER_PORT 8888 //端口号,范围1024~49151
#define SET_IP "192.168.114.85" //本机IP,ifconfig
int do_download(int cfd,struct sockaddr_in sin);
int main(int argc, const char *argv[])
{
//创建报式套接字 socket
int cfd = socket(AF_SOCK_DGRAM,0);
if(cfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("socket create success cfd=%d\n",cfd);
//填充服务器的地址信息结构体,给sendto函数使用
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port =htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(SER_IP);
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);//循环吸收垃圾字符,直到吸收到\n字符
switch(choose)
{
case '1':
do_download(cfd,sin);
break;
case '2':
break;
case '3':
goto END;
break;
default:
printf("输入错误,请重新输入\n");
break;
}
printf("输入任意字符清屏");
while(getchar()!=10);
}
END:
//关闭套接字
close(cfd);
return 0;
}
int do_download(int cfd,struct sockaddr_in sin)
{
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* ptr4 = ptr2+strlen(filename)+1;
strcpy(ptr4,"octet");
int size = 2+strlen(ptr2)+1+strlen(ptr4)+1;
if(sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto download request success\n");
while(1)
{
//接收数据 recvfrom,接收地址信息
//组ACK包
//发送ACK sendto
//判断数据是否小于512个字节,若小于则下载完成
}
return 0;
}
2、思维导图