#include<myhead.h>
#define SER_PORT 69
#define SER_IP "192.168.122.17"
int main(int argc, const char *argv[])
{ int ikun;
printf("********1.下载********\n");
printf("********2.上传********\n");
printf("********3.退出********\n");
scanf("%d",&ikun);
switch(ikun)
{
case 1:
{
char name[20]="";
printf("请输入要下载的文件>>\n");
read(0,name,sizeof(name));
name[strlen(name)-1]=0;
int fp=-1;
if((fp=open(name,O_WRONLY|O_CREAT|O_TRUNC,0664)) ==-1)
{
perror("open error");
return -1;
}
int cfp=socket(AF_INET,SOCK_DGRAM,0);
if(cfp ==-1)
{
perror("socket error");
return -1;
}
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(SER_IP);
socklen_t socklen=sizeof(sin);
char buf[516]="";
short *p1=(short *)buf;
*p1=htons(1);
char *p2=buf+2;
strcpy(p2,name);
char *p3=p2+strlen(p2)+1;
strcpy(p3,"octet");
int len=4+strlen(p2)+strlen(p3);
sendto(cfp,buf,len,0,(struct sockaddr*)&sin,sizeof(sin));
while(1)
{
bzero(buf,sizeof(buf));
//接受数据包
int res=recvfrom(cfp,buf,sizeof(buf),0,(struct sockaddr*)&sin,&socklen);
//未读取完成
if(res==516)
{
char *p=buf+4;
int len1=strlen(p);
short *p4=(short*)buf;
*p4=htons(4);
write(fp,p,len1);
sendto(cfp,buf,4,0,(struct sockaddr*)&sin,sizeof(sin));
}
//读取完成
else if(res<516)
{
write(fp,buf+4,res-4);
printf("读取完成\n");
break;
}
}
close(fp);
close(cfp);
break;
}
case 2:
{
char names[20]="";
printf("请输入要上传的文件>>\n");
read(0,names,sizeof(names));
names[strlen(names)-1]=0;
int fd=-1;
if((fd=open(names,O_RDONLY)) ==-1)
{
perror("open error");
return -1;
}
int cfd=socket(AF_INET,SOCK_DGRAM,0);
if(cfd ==-1)
{
perror("socket error");
return -1;
}
struct sockaddr_in sins;
sins.sin_family=AF_INET;
sins.sin_port=htons(SER_PORT);
sins.sin_addr.s_addr=inet_addr(SER_IP);
socklen_t socklens=sizeof(sins);
char duf[516]="";
short *p11=(short *)duf;
*p11=htons(1);
char *p22=duf+2;
strcpy(p22,names);
char *p33=p22+strlen(p22)+1;
strcpy(p33,"octet");
int lens=4+strlen(p22)+strlen(p33);
sendto(cfd,duf,lens,0,(struct sockaddr*)&sins,sizeof(sins));
int num=1;
while(1)
{
bzero(duf,sizeof(duf));
short *p6=(short *)duf;
short *p66=(short *)duf+2;
*p6=htons(3);
*p66=htons(num);
char *pd=duf+4;
int ress=read(fd,pd,sizeof(pd));
sendto(cfd,duf,sizeof(duf),0,(struct sockaddr*)&sins,sizeof(sins));
num++;
if(ress ==0)
{
printf("上传完成\n");
break;
}
}
close(fd);
close(cfd);
break;
}
case 3:
break;
}
return 0;
}
网络编程上传下载1.16,7
最新推荐文章于 2024-11-17 09:24:48 发布
该篇文章详细描述了一个使用C语言编写的客户端-服务器程序,用于在局域网中实现文件的下载和上传功能,通过UDP套接字进行数据交互。
摘要由CSDN通过智能技术生成