tftp服务器下载功能
#include <myhead.h>
#define IP "192.168.125.160"
#define PORT 69
int main(int argc, const char *argv[])
{
int cfd=-1;
if((cfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket 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);
char buf[516]="";
buf[1]=1;
char *p=buf+2;
char qq[20]="";
printf("请输入要下载的文件名:");
scanf("%s",qq);
strcpy(p,qq);
char *q=p+strlen(p)+1;
strcpy(q,"octet");
int size=4+strlen(p)+strlen(q);
sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin));
puts("发送下载请求");
int fd=-1;
if((fd=open(qq,O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
{
perror("open error");
return -1;
}
struct sockaddr_in cin;
socklen_t len1=sizeof(cin);
char rbuf[516]="";
while(1)
{
bzero(buf,sizeof(buf));
bzero(rbuf,sizeof(rbuf));
int res=recvfrom(cfd,buf,516,0,(struct sockaddr*)&cin,&len1);
if(buf[1]==3)
{
write(fd,buf+4,res-4);
if(res<516)
{
puts("下载完成");
break;
}
strcpy(rbuf,buf);
}
else if(buf[1]==5)
{
printf("出现错误:%s\n",buf+4);
strcpy(buf,rbuf);
}
buf[1]=4;
sendto(cfd,buf,4,0,(struct sockaddr*)&cin,sizeof(cin));
}
close(cfd);
return 0;
}