#include<myhead.h>
int download(int sfd,struct sockaddr_in sin);
int main(int argc, const char *argv[])
{ //创建套接字
int sfd;
sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-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("192.168.114.168");
//菜单
while(1)
{
int mune;
printf("\t\t******1.下载********\n");
printf("\t\t******2.上传********\n");
printf("\t\t******3.退出********\n");
printf("请选择功能\n");
scanf("%d",&mune);
getchar();
switch(mune)
{
case 1:
{
download(sfd,sin);
}
break;
case 2:
{
upload(sfd,sin);
}
break;
case 3:
goto ea;
default:
printf("请输入正确选项\n");
break;
}
}
ea:
return 0;
}
//下载
int download(int sfd,struct sockaddr_in sin)
{
char buf[516]="";
char name[40]="";
buf[1]=1;
char *p1=buf+2;
printf("文件名:");
scanf("%s",name);
getchar();
strcpy(p1,name);
char *p2=p1+strlen(name)+1;
strcpy(p2,"octet");
int size=4+strlen(name)+strlen(p2);
if(sendto(sfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("sendto error");
return -1;
}
int fd=-1;
if((fd=open(p1,O_WRONLY|O_CREAT|O_TRUNC,0666))==-1)
{
perror("open error");
return -1;
}
struct sockaddr_in cin;
cin.sin_family=AF_INET;
socklen_t socklen=sizeof(cin);
int rs;
while(1)
{
bzero(buf,sizeof(buf));
if((rs=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&socklen))==-1)
{
perror("recvfrom error");
return -1;
}
printf("接收成功\n");
write(fd,&buf[4],rs-4);
buf[1]=4;
if(sendto(sfd,buf,4,0,(struct sockaddr*)&cin,sizeof(cin))==-1)
{
perror("ack sendto error");
return -1;
}
printf("ack返回\n");
if(rs<516)
break;
}
return 0;
}