#include <myhead.h>
#define SEP_IP
#define SEP_PORT
int main(int argc, const char *argv[])
{//创建套接字if(int crd=socket(AF_INET,SOCK-DGRAM)==-1);{perror("socket error");return -1;}printf("创建成功\n");//填充地址struct sockaddr_in sin;sin.sin_family=AF_INET;sin.sin_port=htons(SEP_PORT);sin.sin_addr.s_addr=inet_addr(SEP_PORT);//收发数据int flg=0;int sum=0;printf("请输入>>>下载(1)>>>发送(2)");scanf("%d",&flg);//下载if(flg==1){fp=open("8.c",O_RDWR | O_CREAT,0664);char buf[516]="";char auf[30]="";char *pa=auf;short *p=(short*)buf;*p=htons(1);char *p2=buf;p2=p2+2;strcpy(p2,"argv[1]");char *p4=p2+strlen(p2)+1;strcpy(p4,"octet");int buf_siezo=strlen(p2)+strlen(p4)+4;sendto(crd,buf,buf_siezo,0,(struct sockaddr*)&sin,sizeof(sin));bzero(buf,sizeof(buf));while(1){if(strlen(buf)<516){printf("最后一次发送");sum=1;}//读取buf中字符写入文件中read(crd,buf+4,sizeof(buf)-4);if(int res=write(fd,buf+4,512)==-1);{perror("write error");}//获取快编号char *p5=buf+2;for(int i=0;i<2;i++){*(pa+i)=*p5;p5++;}bzero(buf,sizeof(buf));//编写akfshort *p6=buf;*p6=htons(4);char *p7=buf+2;for(int j=0;j<2;j++){*p7=*(pa+j);p7++;}//发送akf包buf_siezo1=4;sendto(crd,buf,buf_siezo1,0,(struct sockaddr*)&sin,sizeof(sin));bzero(buf,sizeof(buf));if(sum==1){printf("下载完成");break;}}close(fp);}//发送if(flg=2){char cuf[516]="";char duf[30]="";char fun[30]="";char *pb=duf+2;short *pp=(short*)cuf;int k=1;int f=0;*pp=htons(2);char *p2=cuf;p2=p2+2;strcpy(p2,"argv[1]");char *p4=p2+strlen(p2)+1;strcpy(p4,"octet");int cuf_siezo=strlen(p2)+strlen(p4)+4;sendto(crd,cuf,cuf_siezo,0,(struct sockaddr*)&sin,sizeof(sin));//bzero(cuf,sizeof(cuf));//获取akffd=fopen("1.c","r+");while(1){//判断是否接接受到ack,如果未收到重新发送read(crd,fun,sizeof(fun))while(1){if(fun[3]==duf[3] && fun[4]==duf[4]){sendto(crd,cuf,sizeof(cuf),0,(struct sockaddr*)&sin,sizeof(sin));sleep(1);}break;}bzero(cuf,sizeof(cuf));bzero(duf,sizeof(duf));bzero(fun,sizeof(fun));if(f=1){break;}read(crd,duf,sizeof(duf));//提取akf,编写数据包short *p8=cuf;*p8=htons(4);char *p9=cuf+2;for(int j=0;j<2;j++){*p9=*(pb+j);p9++;}//打开文件,编写数据包int temp=read(fd,(cuf+4+512*k),512);k++;//返回值判断是否最后一次发送if(temp<512){printf("最后一次发送");f=1;}sendto(crd,cuf,516,0,(struct sockaddr*)&sin,sizeof(sin));}close(fd);}return 0;
}