TFTP是个十分简单的基于UDP的传输协议,因为TFTP本身很大的局限性,比如传输的文件本身受32M的限制,传输效率低下等等,
最近刚好用上TFTP的服务器端,本来想到协议十分简单,随便从网上下载一个源代码来使用,最终没找到合适的,所以求人还不如求自己。
//*****************tftp_svr.h头文件,只提供两个导出函数,tftpd_create用于创建TFTP服务器端,*************************/
///ByFanxiushu-09-19#pragmaoncevoid*tftpd_create(constchar*strip,intport,constchar*root_path);voidtftpd_close(void*handle);
///*****************tftp_svr.cpp实现文件,最下面有代码的使用例子,非常简单*********************************/
///ByFanxiushu-09-19#include#include#include#include"tftp_svr.h"#include#include#includeusingnamespacestd;//根据IP:PORT来区分每个客户请求structtftpd_client{unsignedintc_ip;unsignedshortc_port;///_code;//1readfile;2writefilestringfullpath;//文件完整路径FILE*fp;boolb_plete;//传输是否成功完成time_tlast_time;//最后一次活动的时间,用来进行超时判断charbuf[550];intsend_size;//重试的时候发生的数据包长度,一般都是516,除非是文件结束op_code=op_code;this->c_ip=c_ip;this->c_port=c_port;fp=NULL;b_plete=false;last_time=time
(0);block_id=0;}~tftpd_client(){close();}};structtftpd{protected:boolquit;intsock;unsignedintbind_localip;intbind_localport;charroot_path[512];///listclients;//正在传输文件的客户端intcreate_tftpd_sock();voidcheck_timeout();intrecv_packet(char*buf,intlen,sockaddr_in*from);voidparse_packet(char*buf,intlen,sockaddr_in*from);voidstart_transfile(tftpd_client*c,char*path,sockaddr_in*from);voidreply_error(interr_code,constchar*errmsg,sockaddr_in*from);voidsend_data_block(tftpd_client*c,sockaddr_in*from);voidrecv_data_block(tftpd_client*c,intblock_id,char*data,intdata_size,sockaddr_in*from);HANDLEhthread;staticunsignedint__stdcall__tftpd_thread(void*p){tftpd*svr=(tftpd*)p;svr->tftpd_loop();return0;}voidtftpd_loop();public:tftpd();~tftpd();///intcreate(constchar*strip,intport,constchar*root_path);};tftpd::tftpd(){quit=false;sock=-1;bind_localip=0;bind_localport=69;//TFTPstrcpy(root_path,"/");}tftpd::~tftpd(){quit=true;closesocket(sock);WaitForSingleObject(hthread,30*000);CloseHandle(hthread);for(list::iteratorit=clients.begin();it!=clients.end(); it){delete*it;}clients.clear();}inttftpd::create_tftpd_sock(){if(sock>=0)closesocket(sock);sock=socket(AF_INET,SOCK_DGRAM,0);if(sock=10){last=cur;check_timeout();//定时超时检查}//intr=recv_packet(buf,,