#include<myhead.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__:",__LINE__);\
perror(msg);\
}while(0)
#define SER_PORT 69 //指定要将数据发给谁,填谁的端口号
#define SER_IP "192.168.223.1" //指定要将数据发给谁,填谁的IP
//下载
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; //&buf[2] //(char*)(ptr1+1)
strcpy(ptr2,filename); //组名字
char* ptr3=ptr2+strlen(filename)+1;
strcpy(ptr3,"octet"); //组模式
int size=2+strlen(ptr2)+1+strlen(ptr3)+1;
//发送下载请求包
if(sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto download request success\n");
struct sockaddr_in rcvaddr; //存储发送方的地址信息
socklen_t addrlen=sizeof(rcvaddr);
while(1)
{
bzero(buf,sizeof(buf));
//接收数据recvfrom,接收地址信息
if(recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&rcvaddr,&addrlen)<0)
{
ERR_MSG("recv");
return -1;
}
//组ACK包
char str[128]="";
unsigned short num=0;
printf("请输入块编码>>>");
scanf("%hd",&num);
unsigned short* p1=(unsigned short*)str;
*p1=htons(4);
unsigned short *p2=(unsigned short*)str+2;
*p2=num;
//发送ACK包
if(sendto(cfd,str,4,0,(struct sockaddr*)&rcvaddr,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto download request success\n");
//判断数据是否小于512个字节,若小于则下载完成
if(addrlen<512)
{
break;
}
}
return 0;
}
int main(int argc, const char *argv[])
{
//创建报式套接字 socket
int cfd=socket(AF_INET,SOCK_DGRAM,0);
if(cfd<0)
{
ERR_MSG("socket");
return -1;
}
printf("socket create success cfd=%d\n",cfd);
//填充服务器的地址信息结构体,给sendto函数使用
//真实的地址信息结构体根据地址族指定,AF_INET:man 7 IP
struct sockaddr_in sin;
sin.sin_family=AF_INET; //必须填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); //循环吸收垃圾字符
switch(choose)
{
case '1':
do_download(cfd,sin);
break;
case '2':
//do_upload();
break;
case '3':
goto END;
break;
default:
printf("输入错误,请重新输入\n");
break;
}
printf("请输入任意字符清屏>>>");
while(getchar()!=10);
}
END:
//关闭套接字
close(cfd);
return 0;
}
网络编程day3作业
最新推荐文章于 2024-11-10 22:52:20 发布