2023-5-21作业补
搭建客户端从客户端将文件上传至服务器!
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#define ERR_MSG(msg) do{printf("line:%d\n",__LINE__);perror(msg);}while(0);
#define PORT 69
#define IP "192.168.8.253"
#define N 4096*6+4
int do_upload(int sfd,struct sockaddr_in sin)
{
//打开文件指定
int fd=open("Server",O_RDONLY);
if(fd<0)
{
if(errno==ENOENT){printf("The file does no exist!\n");return -2;}
else{ERR_MSG("open");return -1;}
}
//上传连接服务器
char buf[N]="";
int size=sprintf(buf,"%c%c%s%c%s%c",0,2,"Server",0,"octet",0);
if(sendto(sfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{ERR_MSG("sendto");return -1;}
//传送文件到服务器
ssize_t recv_len=0;
unsigned short num=0;
socklen_t addrlen=sizeof(sin);
while(1)
{
bzero(buf,N);
recv_len=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&addrlen);
if(recv_len<0){ERR_MSG("recvfrom");return -1;}
if(4==buf[1])
{
if(num==ntohs(*(unsigned short*)(buf+2)))
{
buf[1]=3;num++;
*(unsigned short*)(buf+2)=htons(num);
int res=read(fd,buf+4,N+4);
if(res<0){ERR_MSG("read");return -1;}
else if(0==res)
{printf("The file has been uploaded!\n");break;}
if(sendto(sfd,buf,res+4,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{ERR_MSG("sendto");return -1;}
}
//提示下载完毕
else{printf("Failed to upload file!\n");break;}
}
//打印错误信息并退出
else if(5==buf[1])
{printf("Error!%s\n",buf+4);break;}
}
//关闭文件
if(close(fd)<0)
{ERR_MSG("close");return -1;}
return 0;
}
int main(int argc, const char *argv[])
{
//创建报式套接字
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd<0)
{ERR_MSG("socket");return -1;}
printf("The data_socket is create success! sfd=%d __%d__\n",sfd,__LINE__);
//填充服务器IP和端口号
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
char choice=0;
while(1)
{
//上传和退出
printf("ooo 1.Upload ooo\nooooo 2.Exit ooooo\n");
printf("ooooooo ");
choice=getchar();while(getchar()!=10);
switch(choice)
{case '1':do_upload(sfd,sin);break;
case '2':printf("Upload termination!\n");goto END;break;}
}
END:
close(sfd);
return 0;
}