tftp服务器下载功能

2023-12-19 23:00:56

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;
}

文章来源:https://blog.csdn.net/m0_64059184/article/details/135095227
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。