1. 将UDP服务器客户端脱离笔记重新搭建(上交)
2. 完成下载上传(上交,必须完成下载,上传尽力完成)
ubuntu@ubuntu:~/INTER/day3/lianxi$ gcc download.c
ubuntu@ubuntu:~/INTER/day3/lianxi$ ./a.out
请输入要下载的文件名>>>1_armcli.c
-----文件下载完毕!!-----
ubuntu@ubuntu:~/INTER/day3/lianxi$ ls
01test.c 1_armcli.c 1_udpSer.c a.out download.c
ubuntu@ubuntu:~/INTER/day3/lianxi$ cat download.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
#define ERR_MSG(msg) do{\
perror(msg);\
printf("%d %s %s\n", __LINE__, __func__, __FILE__);\
}while(0)
#define PORT 69
#define IP "192.168.1.18"
//下载功能
int do_download(int sfd, struct sockaddr_in sin)
{
char filename[20] = "";
printf("请输入要下载的文件名>>>");
scanf("%s",filename);
//发送下载请求
char buf[516] = "";
int size = sprintf(buf, "%c%c%s%c%s%c", 0, 1, filename, 0, "octet", 0);
if(sendto(sfd, buf, size, 0, (struct sockaddr*)&sin, sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
int flag = 0;
int fd ;
//循环接收发送应答包
ssize_t recv_len;
unsigned short num = 1;
socklen_t addrlen = sizeof(sin);
while(1)
{
bzero(buf,516 );
recv_len = recvfrom(sfd, buf, 516, 0, (struct sockaddr*)&sin, &addrlen);
if(recv_len < 0)
{
ERR_MSG("recvfrom");
return -1;
}
if(3 == buf[1]) //如果是数据包
{
if(0 == flag) //防止文件重复打开
{
//存储从服务器下载下来的文件,接收数据成功后再创建数据;
//创建并打开filename文件
fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd < 0)
{
ERR_MSG("open");
return -1;
}
flag = 1;
}
//判断当前的快编号
if(htons(num) == *(unsigned short*)(buf+2)) //防止数据包重复到达
{
if(write(fd, buf+4, recv_len-4) < 0)
{
printf("fd:%d recv_len=%ld\n", fd, recv_len);
ERR_MSG("write");
break;
}
//回复ack包
buf[1] = 4;
if(sendto(sfd, buf, 4, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("sendto");
}
//判断数据包的大小是否小于 512+2+2;
if(recv_len < 512+2+2)
{
printf("-----文件下载完毕!!-----\n");
break;
}
num++;
}
}
else if(5 == buf[1]) //错误包
{
//打印错误信息
printf("-----ERROR:%s-----\n", buf+4);
break;
}
}
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;
}
struct sockaddr_in sin;
sin.sin_family =AF_INET;
sin.sin_port =htons(PORT);
sin.sin_addr.s_addr =inet_addr(IP);
//下载功能
do_download(sfd,sin);
return 0;
}