基于UDP的TFTP文件传输
#include <myhead.h>
#define SER_PORT 69
#define SER_IP "192.168.125.64"
int main(int argc, const char *argv[])
{
//以写的形式打开要写入的文件
int fd=-1;
if((fd=open("./5.png",O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("open error");
return -1;
}
//创建用于通信的套接字文件描述符
int cfd = socket(AF_INET,SOCK_DGRAM,0);
if(cfd==-1)
{
perror("socket error");
return -1;
}
//填充服务器的地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port= htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
socklen_t socklen = sizeof(sin);
//向服务器发送下载请求
short str=0;
char buf[516]="";
//组装请求数据
short *p1 = (short *)buf;
*p1 =htons(1);
char *p2 = buf+2;
strcpy(p2,"5.png");
char *p3=p2+strlen(p2)+1;
strcpy(p3,"octet");
int len =4+strlen(p2)+strlen(p3);
//向服务器发送请求
sendto(cfd,buf,len,0,(struct sockaddr*)&sin,sizeof(sin));
while(1)
{
bzero(buf,sizeof(buf));
//向后移动指针,读取数据
lseek(cfd,4,SEEK_SET);
int res=recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&socklen);
char *sbuf=buf+4;
write(fd,sbuf,res-4);
printf("%d\n",res);
//判断是否拷贝完成
if(res<516)
{
break;
}
bzero(buf,sizeof(buf));
short *p1 = (short *)buf;
*p1 =htons(4);
short *p2 = (short *)(buf+2);
str++;
*p2=htons(str);
printf("%d\n",str);
len =4;
//发送ACK,继续拷贝
sendto(cfd,buf,len,0,(struct sockaddr*)&sin,sizeof(sin));
}
//关闭套接字
close(cfd);
//关闭文件指针
close(fd);
return 0;
}