- /******************************************************
- 功能:可以从tftp服务器下载文件
- 命令格式:./tftp 192.168.221.x 文件名
- 时间:2012-04-25
- ******************************************************/
- #include<stdio.h>
- #include<unistd.h>
- #include<stdlib.h>
- #include<arpa/inet.h>
- #include<netinet/in.h>
- #include<sys/socket.h>
- #include<string.h>
- #include<errno.h>
- #include <netdb.h>
- #include<sys/types.h>
- #include<sys/stat.h>
- #include<fcntl.h>
- int main(int argc, char *argv[])
- {
- int fp;
- int sockfd = 0;
- int i=0,fd;
- unsigned short port = 69;
- struct sockaddr_in cliaddr;
- struct sockaddr_in recvddr;
- char buf[1024] = "";
- struct hostent *host;
- int ret;
- fp = open(argv[2],O_WRONLY|O_CREAT); //创建打开文件
- if((host = gethostbyname(argv[1])) == NULL) //从输入端获取IP
- {
- fprintf(stderr, "Gethostname error\n");
- exit(1);
- }
- if(argc < 1)
- {
- printf("You not input IP and filename!\n");
- exit(1);
- }
- bzero(&cliaddr, sizeof(cliaddr));
- cliaddr.sin_family = AF_INET;
- cliaddr.sin_port = htons(port);
- cliaddr.sin_addr = *((struct in_addr *)host->h_addr);
-
- if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) //创建套接字
- {
- perror("socket error\n");
- exit(1);
- }
- ret = sprintf(buf, "%c%c%s%c%s%c", 0, 1,argv[2], 0, "octet", 0); //传送命令,请求下载文件
- sendto(sockfd, buf, ret, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
- while(1)
- {
- char sendbuf[1024] = "";
- size_t len = 0;
- unsigned int recvddr_len = sizeof(struct sockaddr);
- bzero(&sendbuf, sizeof(sendbuf));
- bzero(&buf, sizeof(buf));
- len = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&recvddr, &recvddr_len) ;
- if(buf[1] == 5)
- {
- printf("%s\n",buf+4);
- unlink(argv[2]); //如果服务器没有那个文件,防止创建空文件
- exit(1);
- }
- if(buf[1] == 3)
- {
- fd = sprintf(sendbuf, "%c%c%c%c", buf[0], buf[1]+1, buf[2], buf[3]); //接到数据后发送ACK确认
- sendto(sockfd, sendbuf, fd, 0, (struct sockaddr *)&recvddr, sizeof(recvddr));
- if((unsigned short)(i+1) == ntohs(*(unsigned short*)(buf+2)))
- {
- write(fp, (buf+4), (len-4)); //这个地方很重要,大小一定要确定好
- i = ntohs(*(unsigned short*)(buf+2));
- printf("recv:%d\n",i);
- }
-
- }
- if(len < 516)
- {
- printf("Accept finished!\n");
- close(fp);
- close(sockfd);
- exit(1);
- }
- }
- return 0;
- }
自己写的一个客户端下载文件程序
最新推荐文章于 2021-09-24 18:06:00 发布