下载效果
?
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
#define SER_IP "192.168.125.149"
#define SER_PORT 69
int main(int argc, const char *argv[])
{
int fd=open("./5.png",O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd<0)
{
perror("fd");
return -1;
}
//套接字通信
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("sfd");
return -1;
}
//服务器端口,ip
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(SER_IP);
socklen_t socklen=sizeof(sin);
//不绑定
//装载读写请求
char buf[516];
short *p1=(short*)buf;
*p1=htons(1); //读请求
char *p2=buf+2;
strcpy(p2,"5.png");
char *p3=p2+strlen(p2)+1;
strcpy(p3,"octet");
int len = 4+strlen(p2)+strlen(p3);
//发送请求
sendto(sfd,buf,len,0,(struct sockaddr*)&sin,socklen);
int res=0;
while(1)
{
bzero(buf,sizeof(buf));
res=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,&socklen);
printf("%d\n",res);
if(res<516)
{
write(fd,buf+4,res-4);
break;
}
write(fd,buf,res-4);
//ack
char ack[4];
short *ack1=(short*)ack;
*ack1=htons(4);
ack[2]=buf[2];
ack[3]=buf[3];
sendto(sfd,ack,4,0,(struct sockaddr*)&sin,sizeof(sin));
}
//关闭文件
close(sfd);
return 0;
}