12-19

#include 
int do_download(int cfd,struct sockaddr_in sin)
{
	char buf[516]="";
	char fileName[40]="";
	printf("请输入文件名: ");
	scanf("%s",fileName);
	getchar();

	short *p1=(short*)buf;
	*p1=htons(1);

	char *p2=buf+2;
	strcpy(p2,fileName);

	char *p4=p2+strlen(p2)+1;
	strcpy(p4,"octet");
	
	int size=4+strlen(p2)+strlen(p4);
	if(sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
		perror("sendto error");
		return -1;
	}
	printf("请求成功\n");
	struct sockaddr_in cin;
	socklen_t socklen=sizeof(cin);
	int res;
	int fd=-1;
	if((fd=open(fileName,O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
	{
		perror("open error");
		return -1;
	}
	while(1)
	{
		bzero(buf,sizeof(buf));
		res=recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&socklen);
		if(buf[1]==3)//当接收到操作码为3的数据包时
		{
			write(fd,buf+4,res-4);
			buf[1]=4;//置操作码为4
			if(sendto(cfd,buf,4,0,(struct sockaddr*)&cin,sizeof(cin))==-1)//返回ACK
			{
				perror("sendto error");
				return -1;
			}
		}
		else if(buf[1]==5)//如果操作码为5
		{
			printf("error\n");
			return -1;
		}
		if(res<516)
		{
			puts("传输完毕!\n");
			close(fd);
			break;
		}
	}

}
int main(int argc, const char *argv[])
{
	if(argc!=2)
	{
		printf("input error\n");
		printf("usage:./a/out ip\n");
		return -1;
	}
	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(69);
		sin.sin_addr.s_addr=inet_addr(argv[1]);

		int mune=-1;
		while(1)
		{
			system("clear");
			printf("\t\t======1、下载======\n");
			printf("\t\t======2、上传======\n");
			printf("\t\t======3、退出======\n");
			printf("请输入功能: ");
			scanf("%d",&mune);
			getchar();

			switch(mune)
			{
			case 1:
				{
					do_download(cfd,sin);
				}
				break;
			case 2:
				{
					//do_upload();
				}
				break;
			case 0:
				goto POS;
			default:printf("输入功能有误,请重新输入\n");
			}
			printf("输入任意键,按回车清空:");
			while(getchar()!='\n');
		}
		POS:
	close(cfd);
	return 0;
}

12-19_第1张图片

你可能感兴趣的:(c语言)