#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);//将数据写到文件中
//发送ACK
rbuf[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;
}
没写完,后面会进行整改