hw0920

#include 
#define PORT 69
#define IP "192.168.125.227"
int do_download(int cfd,struct sockaddr_in sin);
int main(int argc, const char *argv[])
{
	//创建流式套接字
	int cfd=socket(AF_INET,SOCK_DGRAM,0);
	printf("socket success\n");
	//允许端口被重复使用
	int reuse=1;
	setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0;
	printf("允许端口被重复使用\n");
	//服务器地址
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(PORT);
	sin.sin_addr.s_addr=inet_addr(IP);

	char choose=0;
	while(1)
	{
		printf("------\n");
		printf("1.下载\n");
		printf("2.上传\n");
		printf("3.退出\n");
		printf("------\n");
		printf("输入:");
		choose=getchar();
		while(getchar()!='\n');
		{
			switch(choose)
			{
			case'1':do_download(cfd,sin);
					break;
			case'2'://do_uoload(cfd,sin);
					break;//上传
			case'3':goto END;//退出
			}
		}
	}
END:
	close(cfd);
	return 0;
}
int do_download(int cfd,struct sockaddr_in sin)
{
	//组下载协议
	char name[20];
	printf("输入文件名\n");
	scanf("%s",name);

	char buf[516];
	unsigned short* p1=(unsigned short*)buf;
	*p1=htons(1);
	char *p2=buf+2;
	strcpy(p2,name);
	char *p3=p2+strlen(name);
	char *p4=p3+1;
	strcpy(p4,"octet");
	int size=2+strlen(p2)+1+strlen(p4)+1;
	//发送下载协议给服务器
	sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin));
	printf("send success");
	socklen_t addrlen=sizeof(sin);
	struct sockaddr_in cin;
	int fd=3;
	int res;
	while(1)
	{
		//接收数据包
		bzero(buf,sizeof(buf));
		res=recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&addrlen);
		printf("buf[1]=%d\n",buf[1]);
		if(buf[1]==5)
		{
			printf("%s\n",buf+4);
			break;
		}
		if(3==buf[1])//判断数据包操作码
		{
			if(*(unsigned short*)(buf+2)==ntohs(1))//操作码为1时打开文件
			{
				fd=open(name,O_RDWR|O_CREAT|O_TRUNC,0664);
			}
			write(fd,buf+4,sizeof(buf)-4);
			//组AK包
			buf[1]=4;
			//回复ACK
			sendto(cfd,buf,4,0,(struct sockaddr*)&cin,addrlen);
			//判断数据是否小于512,若小于512则结束下载
			if(res-4<512)
			{
				printf("文件拷贝完毕\n");
				break;
			}
		}
	}
	close(fd);
	return 0;
}

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