tftpd
#include <myhead.h>
#define SER_IP "192.168.125.243" //服务器IP地址
#define SER_PORT 69 //服务器端口号
#define CLI_IP "192.168.125.244" //客户端IP地址
#define CLI_PORT 8889 //客户端端口号
int main(int argc, const char *argv[])
{//创建用于通信的套接字文件描述符int cfd = socket(AF_INET, SOCK_DGRAM, 0);if(cfd == -1){perror("socket error");return -1;}printf("socket success sfd = %d\n", cfd);//绑定IP地址和端口号struct sockaddr_in cin;cin.sin_family = AF_INET;cin.sin_port = htons(CLI_PORT);cin.sin_addr.s_addr = inet_addr(CLI_IP);if(bind(cfd, (struct sockaddr*)&cin, sizeof(cin)) == -1){perror("bind error");return -1;}printf("bind success\n");//服务端信息结构体struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(SER_PORT);sin.sin_addr.s_addr = inet_addr(SER_IP);//接收文件char data[516] = {0};short *p1=data;*p1=htons(1);char *p2=data+2;strcpy(p2,"5.png");char *p4=p2+strlen(p2)+1;strcpy(p4,"octet");int req_size=4+strlen(p2)+strlen(p4);sendto(cfd,data,req_size,0,(struct sockaddr*)&sin,sizeof(sin));int fd=open("./5.png",O_WRONLY|O_CREAT|O_TRUNC,0777);if(fd==-1){perror("open err");return -1;}while(1){bzero(data,sizeof(data));recv(cfd,data,sizeof(data),0);short *b=data+2;char ack[4]={0};short *q1=ack;*q1=htons(4);short *q2=ack+2;*q2=*b;sendto(cfd,ack,4,0,(struct sockaddr*)&sin,sizeof(sin)); write(fd,data,sizeof(data));int len=strlen(data);if(len<515)break;}close(fd);close(cfd);return 0;
}