博主:经测试,能够使用
最近学习LINUX socket编程,利用socket实现了一个Linux下命令行的tftp客户端,此客户端只可以从TFTP服务器获取文件。使用格式为:./tftpget 。该程序可以运行在Linux的PC机上,也可以运行在嵌入式开发板上(需交叉编译)。程序的源代码及其注释如下:
//下面定义的几个宏是TFTP协议的操作码,参考协议 #define OP_RRQ 1 //读请求 #define OP_WRQ 2 //写请求 #define OP_DATA 3 //数据包 #define OP_ACK 4 //确认包 #define OP_ERROR 5 //错误信息 //TFTP错误信息编码 static char *error_string[] = { "File not found!", //1 "Access denied!", //2 "Disk full or allocation exceeded!", //3 "Illegal TFTP operation!", //4 "Unknown transfer ID!", //5 "File already exists!", //6 "No such user!" //7 }; int main(int argc, char **argv) struct sockaddr_in tftpServer, tftpClient; //自身和服务器的socket信息 FILE *fp; //用于保存本地文件 char buffer[516]; //网络通信用的buffer int addrlen; unsigned short *s_ptr; if (argc { printf("Usage: %s n", argv[0]); //创建socket socketFD = socket(AF_INET, SOCK_DGRAM, 0); //客户端自身信息 bzero(&tftpClient, sizeof (tftpClient)); //绑定socket到本机IP地址 tmp = bind(socketFD, (struct sockaddr *)&tftpClient, sizeof (tftpClient)); //服务器信息 bzero(&tftpServer, sizeof (tftpServer)); s_ptr = (unsigned short *)&buffer[0]; c_ptr = &buffer[2]; strcpy(&buffer[2], argv[2]); //远程文件名 c_ptr += strlen(argv[2]); c_ptr += 8; //创建一个本地文件 fp = fopen(argv[2], "w"); lastPacket = 0; while (1) tmp = sendto(socketFD, buffer, c_ptr - &buffer[0], 0, //从服务器获取数据包 tmp = recvfrom(socketFD, buffer, 516, 0, (struct sockaddr *)&tftpServer,&addrlen); case OP_DATA: if ((lastPacket + 1) != currentPacket) lastPacket = currentPacket; tmp -= 4; ret = fwrite(&buffer[4], 1, tmp, fp); //如果等于512则不是最后一个包 if (512 != tmp) //准备返回信息 *s_ptr = htons(OP_ACK); break; //服务器返回错误信息 case OP_ERROR: printf("ERROR: %sn", error_string[ntohs(*(s_ptr+1))]); //发生其他未知错误 default: read_ok: error_2: |