24.1.17 DAY4

24.1.17 DAY4_第1张图片

代码:

  1 #include
  2 #define SER_PORT 69
  3 #define SER_IP "192.168.122.122"
  4 
  5 int main(int argc, const char *argv[])
  6 {
  7     //1、创建用于通信的套接字文件描述符
  8     int cfd = socket(AF_INET, SOCK_DGRAM, 0);
  9     if(cfd == -1)
 10     {
 11         perror("socket error");
 12         return -1;
 13     }
 14 
 15     //2、绑定(可选)
 16 
 17     //3、填充服务器的地址信息结构体
 18     struct sockaddr_in sin;
 19     sin.sin_family = AF_INET;
 20     sin.sin_port = htons(SER_PORT);
 21     sin.sin_addr.s_addr = inet_addr(SER_IP);
 22 
 23     //向服务器发送下载请求
 24     char buf[512] = "";
 25 
 26     //组装请求数据
 27     short *p1 = (short *)buf;
 28     *p1 = htons(1);
 29 
 30     char *p2 = buf+2;
 31     strcpy(p2, "5.png");
 32 
 33     char *p3 = p2+strlen(p2)+1;
 34     strcpy(p3, "octet");
 35 
 36     int len = 4+strlen(p2) + strlen(p3);   //要发送的长度
 37 
 38     //向服务器发送请求
 39     int res=sendto(cfd, buf, len, 0, (struct sockaddr*)&sin, sizeof(sin));
 40     if(res==-1)
 41     {
 42         perror("sendto error");
 43         return -1;
 44     }
 45 
 46 
 47     int i=0;
 48     while(1)
 49     {
 50         i++;
 51         bzero(buf, sizeof(buf));
 52         recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cin, &socklen);
 53         if(*p2==(short)i)
 54         {
 55             int fd = -1;      //定义文件描述符变量
 56             char copyfile[128]="";
 57             gets(copyfile);
 58             copyfile[strlen(copyfile)-1]='0';
 59 
 60             char rbuf[128]="";
 61             fd = open(copyfile, O_RDONLY);
 62             if(fd == -1)
 63             {
 64                perror("open error");
 65                return -1;
 66             }
 67             printf("fd=\n",fd);
 68             int res=read(fd,rbuf,sizeof(rbuf));
 69             if(res==0)
 70                 break;
 71             *p1=3;
 72             *p2=(short)i;
 73             p3 = p2+strlen(p2)+1;
 74             strcpy(p3,rbuf);
 75             len=2+strlen(p2)+strlen(p3);
 76 
 77             sendto(cfd,buf,len,0,(struct sockaddr*)&sin, sizeof(sin));
 78 
 79             close(fd);
 80         }
 81 
 82     }
 83 
 84     //5、关闭套接字
 85     close(cfd);
 86 
 87 
 88     return 0;
 89 }                      

运行结果:

你可能感兴趣的:(算法,数据结构)