#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
int sockfd;
struct sockaddr_in server;
char read_cmd[100]="";
char buf[512]="";
char up_buf[512]="";
int count=0;
int temp;
char block_num[2]="";
int addrlen = sizeof(server);
int fd;
char filename[100]="0";
char filename_temp[100]="0";
char up_temp[516]="";
char ch;
char code;
bzero(&server, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(69);
server.sin_addr.s_addr = inet_addr("192.168.220.37");
printf("please input filename\n");
scanf("%s",filename);
strcpy(filename_temp,filename);
printf("please input opreating code\n1 is download\n2 is upload\n");
scanf("%s",&ch);
// sprintf(read_cmd,"%c%c%s%c%s%c",0,ch,filename,0,"octet",0);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0)
{
perror("Invalid socket");
exit(1);
}
// sendto(sockfd, read_cmd, 18, 0, (struct sockaddr*)&server, sizeof(struct sockaddr));
if(ch=='1')
{
sprintf(read_cmd,"%c%c%s%c%s%c",0,1,filename,0,"octet",0);
sendto(sockfd, read_cmd, 18, 0, (struct sockaddr*)&server, sizeof(struct sockaddr));
count=recvfrom(sockfd, buf, 512, 0, (struct sockaddr*)&server, &addrlen);
printf("%d\n",count);
if((buf[1]==5))
{
printf("FILE NOT FIND\n");
printf("buf=%s\n",buf+4);
exit(1);
}
if((fd = open(filename, O_RDWR|O_CREAT))<0)
{
printf("filename=%s\n",filename_temp);
perror("open");
exit(1);
}
while(count>=512)
{
write(fd,buf+4,strlen(buf+4));
block_num[0]=buf[2];
block_num[1]=buf[3];
sendto(sockfd,block_num,2,0,(struct sockaddr*)&server,sizeof(struct sockaddr));
memset(buf,0,512);
count=recvfrom(sockfd, buf, 512, 0, (struct sockaddr*)&server, &addrlen);
}
write(fd,buf+4,strlen(buf+4));
close(fd);
return 0;
}
if(ch=='2')
{
sprintf(read_cmd,"%c%c%s%c%s%c",0,2,filename,0,"octet",0);
// sprintf(up_temp,"%c%c%c%c",0,3,0,1);
printf("up_temp=%d\n",up_temp[1]);
sendto(sockfd, read_cmd, 9+strlen(filename), 0, (struct sockaddr*)&server, sizeof(struct sockaddr));
recvfrom(sockfd, buf, 512, 0, (struct sockaddr*)&server, &addrlen);
if((buf[1]==5))
{
printf("FILE NOT FIND\n");
printf("buf=%s\n",buf+4);
exit(1);
}
if((fd = open(filename, O_RDWR))<0)
{
perror("open");
exit(1);
}
count=read(fd,up_buf,512);
code=1;
while (count>0)
{
int i=0;
// printf("up_buf=%s\n",up_buf);
// strcat(up_temp,up_buf);
sprintf(up_temp, "%c%c%c%c%s", 0,3,0,code,up_buf);
sendto(sockfd,up_temp,516,0,(struct sockaddr*)&server,sizeof(struct sockaddr));
recvfrom(sockfd, buf, 512, 0, (struct sockaddr*)&server, &addrlen);
block_num[0]=buf[2];
block_num[1]=buf[3];
printf("buf[3]=%s\n",buf+3);
count=read(fd,up_buf,512);
code++;
memset(buf,0,512);
memset(up_temp,0,516);
}
}
}
阅读(607) | 评论(0) | 转发(0) |