#define SER_PORT 69
#define SER_IP "192.168.125.71"
#define CLT_PORT 6666
#define CLT_IP "192.168.125.158"
int main(int argc, const char *argv[])
{//创建套接字文件描述符int cfd = socket(AF_INET,SOCK_DGRAM,0);if(cfd == -1){perror("socket error");return -1;}printf("cfd = %d\n",cfd);//3数据收发
// char rbuf[128] = "";//填充服务器的地址信息结构体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 buf[516] = "";char rbuf[516] = "";//组装操作码short*p1 = (short*)buf;*p1 = htons(1);//组装文件名char *p2 = buf+2;strcpy(p2,"5.png");//组装传输模式char *p4 = p2+strlen(p2)+1;strcpy(p4,"octet");int size = 2+strlen(p2)+strlen(p4)+2;//将协议包发送给服务器sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin));socklen_t addrlen = sizeof(sin);unsigned short block_num = 1; //定义本地块编号while(1){//接收服务器传回来的信息int res = recvfrom(cfd,rbuf,sizeof(rbuf),0,(struct sockaddr*)&sin,&addrlen);if(res == -1){perror("recvfrom error");return -1;}if(rbuf[1] == 3){if(*(unsigned short*)(buf+2) == htons(block_num)){block_num++;//块编号自增int fd = open("./1",O_WRONLY|O_CREAT|O_TRUNC,0666);write(fd,rbuf+4,sizeof(rbuf+4);//将数据写到文件中//发送ACKrbuf[1] = 4; sendto(cfd,rbuf,4,0,(struct sockaddr*)&sin,sizeof(sin));printf("%s 文件下载完毕");}}/*//将网络字节序转换为主机字节序unsigned short int value_net = htons(rbuf[1]);printf("%#x\n",value_net);*/}//4关闭套接字close(cfd);return 0;
}
没写完,后面会进行整改