用udp实现tftp下载和上传功能
cpp
#include <myhead.h>
#define PORT 69
#define IP "192.168.122.24"
int shangchuan(int sfd,struct sockaddr_in sin,socklen_t socklen)
{
int cfd=-1;
if((cfd=open("./01udpk.c",O_RDONLY))==-1)
{
perror("open error");
return -1;
}
char rbuf[516]="";
short a=1;
int SIZE=sprintf(rbuf,"%c%c%s%c%s%c",0,2,"./01udpk.c",0,"octet",0);
sendto(sfd,rbuf,SIZE,0,(struct sockaddr*)&sin,sizeof(sin));
while(1)
{
recvfrom(sfd,rbuf,sizeof(rbuf),0,(struct sockaddr*)&sin,&socklen);
bzero(rbuf,sizeof(rbuf));
int sre=read(cfd,rbuf+4,512);
if(sre==0)
{
break;
}
short *a1=(short*)rbuf;
*a1=htons(3);
short *a2=(short*)(rbuf+2);
*a2=htons(a++);
sendto(sfd,rbuf,sre+4,0,(struct sockaddr*)&sin,sizeof(sin));
}
close(cfd);
}
int xiazai(int sfd,struct sockaddr_in sin,socklen_t socklen)
{
int fd=-1;
if((fd=open("./helltaker.bmp",O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("open error");
return -1;
}
char buf[516]="";
char ack[4]="";
int len=sprintf(buf,"%c%c%s%c%s%c",0,1,"./helltaker.bmp",0,"octet",0);
sendto(sfd,buf,len,0,(struct sockaddr*)&sin,sizeof(sin));
while(1)
{
bzero(buf,sizeof(buf));
int res=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&socklen);
if(res<516)
{
write(fd,buf+4,res-4);
break;
}
write(fd,buf+4,res-4);
short *q1=(short *)(buf+2);
short *p4=(short *)ack;
*p4=htons(4);
short *p5=(short *)(ack+2);
*p5=*q1;
sendto(sfd,ack,4,0,(struct sockaddr*)&sin,sizeof(sin));
}
printf("下载完成\n");
close(fd);
}
int main(int argc, const char *argv[])
{
int sfd=-1;
if((sfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket error");
return -1;
}
int reuse=-1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
socklen_t socklen=sizeof(sin);
int num;
while(1)
{
printf("\t\t=======1.下载=======\n");
printf("\t\t=======2.上传=======\n");
printf("\t\t=======3.退出=======\n");
printf("请输入功能:");
scanf("%d",&num);
while(getchar()!='\n');
switch(num)
{
case 1:
{
xiazai(sfd,sin,socklen);
}
break;
case 2:
{
shangchuan(sfd,sin,socklen);
}
break;
case 3 :
goto END;
default:printf("输入有误,请重新输入\n");
}
printf("按任意键清屏\n");
while(getchar()!='\n');
system("clear");
}
END:
close(sfd);
return 0;
}