1.16 day3 IO网络编程

用udp实现tftp下载功能

#include 
#define PORT 69
#define IP "192.168.122.24"
int xiazai(int sfd,struct sockaddr_in sin,int fd,socklen_t socklen)
{
	char buf[516]="";
	char ack[4];
	short *p1=(short *)buf;
	*p1=htons(1);
	char *p2=buf+2;
	strcpy(p2,"helltaker.bmp");
	char *p3=p2+strlen(p2)+1;
	strcpy(p3,"octet");
	int len=4+strlen(p2)+strlen(p3);
	sendto(sfd,buf,len,0,(struct sockaddr*)&sin,sizeof(sin));
	while(1)
	{
		bzero(buf,sizeof(buf));
		int res=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&socklen);
		if(res<516)
		{
			write(fd,buf+4,res-4);
			break;
		}
		write(fd,buf+4,res-4);
		short *q1=(short *)(buf+2);

		short *p4=(short *)ack;
		*p4=htons(4);
		short *p5=(short *)(ack+2);
		*p5=*q1;
		sendto(sfd,ack,4,0,(struct sockaddr*)&sin,sizeof(sin));

	}
	printf("下载完成\n");
	return 0;

}
int main(int argc, const char *argv[])
{
	int fd=-1;
	if((fd=open("./helltaker.bmp",O_WRONLY|O_CREAT|O_TRUNC,0664))==-1)
	{
		perror("open error");
		return -1;
	}
	int sfd=-1;
	if((sfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
	{
		perror("socket error");
		return -1;
	}

	int reuse=-1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
	{
		perror("setsockopt 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);
	socklen_t socklen=sizeof(sin);
	int num;
	while(1)
	{
		printf("\t\t=======1.下载=======\n");
		printf("\t\t=======2.上传=======\n");
		printf("\t\t=======3.退出=======\n");
		printf("请输入功能:");
		scanf("%d",&num);
		while(getchar()!='\n');
		switch(num)
		{
			case 1:
				{
					xiazai(sfd,sin,fd,socklen);
				}
				break;
			case 2:
				{
					//shangchuan();
				}
				break;
			case 3 :
goto END;
			default:printf("输入有误,请重新输入\n");
		}
		printf("按任意键清屏\n");
		while(getchar()!='\n');
		system("clear");
	}
END:


	
	return 0;
}

你可能感兴趣的:(网络)