作业内容
TFTP协议实现客户端从服务器下载文件
主函数
#include <stdio.h>
#include <sys/stat.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>
//打印错误新的宏函数
#define ERR_MSG(msg) do{\
fprintf(stderr, " __%d__ ", __LINE__);\
perror(msg);\
}while(0)
//指定要连接的服务器的地址信息
#define PORT 69
#define IP "192.168.31.96" //服务器IP
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);
struct sockaddr_in rcv_addrmsg; //存储接收到的数据包来自哪里
socklen_t addrlen = sizeof(rcv_addrmsg);
//创建读写请求
char request[128] = "";
char* ptr = request;
//操作码
short int* pa = (short int*)ptr;
*pa = htons(1);
//文件名
char* pb = ptr+2;
strcpy(pb,"5.png");
//0
char* pc = pb+strlen(pb);
*pc = 0;
//模式
char* pd = pc+1;
strcpy(pd,"octet");
//计算请求包大小
size_t size = 2 + strlen(pb) + 1 + strlen("octet") + 1;
//发送请求
if(sendto(sfd,request,size,0,(struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
//打开要写入的文件
int fd = open("./1.png",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd < 0)
{
ERR_MSG("open");
return -1;
}
//创建存储数据包的数组
char data[516] = "";
char* dtr = data;
//操作码
short int* pa_d = (short int*)dtr;
//块编号
short int* pb_d = pa_d+1;
//数据
char* pc_d = (char*)(pb_d+1);
//创建ACK
char ack[4] = "";
char* atr = ack;
//操作码
short int* pa_a = (short int*)atr;
//块编号
short int* pb_a = pa_a+1;
while(1)
{
bzero(data,sizeof(data));
//接收数据包
ssize_t res;
if((res=recvfrom(sfd,data,sizeof(data),0,(struct sockaddr*)&rcv_addrmsg,&addrlen)) < 0)
{
ERR_MSG("recvfrom");
return -1;
}
if(res < 516)
{
if(write(fd,pc_d,512) < 0)
{
ERR_MSG("write");
return -1;
}
break;
}
if(write(fd,pc_d,res-4) < 0)
{
ERR_MSG("write");
return -1;
}
//操作码、块编号转换为网络字节序
*pa_a = htons(4);
*pb_a = *pb_d;
//发送ACK
if(sendto(sfd,ack,sizeof(ack),0,(struct sockaddr*)&rcv_addrmsg,addrlen) < 0)
{
ERR_MSG("sendto");
return -1;
}
}
//关闭套接字
close(sfd);
return 0;
}