tftp_download.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PORT 69 //规定端口
#define IP "192.168.8.74" //windowsIP
#define ERR_MSG(msg) do{\
fprintf(stderr,"line:__%d__\n",__LINE__);\
perror(msg);\
return -1;\
}while(0)
int main(int argc, const char *argv[])
{
//创建报式套接字
int socketfd=socket(AF_INET,SOCK_DGRAM,0);
if(socketfd<0)
{
ERR_MSG("socket");
}
//允许端口快速重用
int reuse=1;
if(setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
//填充地址信息结构体
struct sockaddr_in sin; //定义结构体变量
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
//组下载请求协议
char buf[128]="";
short *p1=(short *)buf;
*p1=htons(1);
char *p2=buf+2;
strcpy(p2,argv[1]);
char *p3=p2+strlen(p2);
*p3=0;
char*p4=p3+1;
strcpy(p4,"octet");
int size = 2+strlen(p2)+1+strlen(p4)+1;
//发送读写请求
if(sendto(socketfd,buf,size,0,(struct sockaddr *)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
}
printf("sendto success\n");
//接收数据包协议
int openfd=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664);
if(openfd<0)
{
ERR_MSG("open");
}
printf("open success\n");
char data[516]="";
ssize_t res=0;
int num=0;
struct sockaddr_in cin; //定义结构体变量
socklen_t socklen=sizeof(cin);
while(1)
{
//接收数据包
bzero(data,sizeof(data));
res=recvfrom(socketfd,data,sizeof(data),0,\
(struct sockaddr *)&cin,&socklen);
if(res<0)
{
ERR_MSG("recvfrom");
}
printf("res=%ld接收成功\n",res);
//判断操作码和块编号
short *q1=(short *)data;
short *q2=q1+1;
printf("%d\n",*q1);
printf("%d\n",*q2);
if(*q1!=ntohs(3) || ++num!=ntohs(*q2++))
{
printf("接收失败\n");
}
else
{
if(write(openfd,data+4,res-4)<0)
{
ERR_MSG("write");
}
if((res-4)<512)
{
printf("下载完毕!\n");
break;
}
//发ACK请求
bzero(data,sizeof(data));
short *k1=(short *)data;
*k1=htons(4);
short *k2=k1+1;
*k2=htons(num);
if(sendto(socketfd,data,4,0,(struct sockaddr *)&cin,sizeof(cin))<0)
{
ERR_MSG("sendto");
}
printf("sendto success\n");
}
}
//关闭套接字
close(socketfd);
return 0;
}
通过tftp服务器连接下载
显示下载完毕