1.Utfp下载文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include<sys/stat.h>
#include<fcntl.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"line:__%d__",__LINE__);\
perror(msg);\
}while(0)
#define PORT 69
#define IP "192.168.10.105"
int main(int argc, const char *argv[])
{
//创建报式套接字
int fds=socket(AF_INET,SOCK_DGRAM,0);
if(fds<0)
{
ERR_MSG("socket");
return -1;
}
printf("套接字创建成功\n");
//定义要链接的结构体信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
//组请求协议
char buf[516]="";
char cuf[4]="";
short* ptr1=(short*)buf;
*ptr1=htons(1);
char* ptr2=buf+2;
strcpy(ptr2,"5.png");
char* ptr3=ptr2+strlen(ptr2);
*ptr3=0;
char* ptr4=ptr3+1;
strcpy(ptr4,"octet");
int size=2+strlen(ptr2)+1+strlen(ptr4)+1;
//临时端口
struct sockaddr_in sin1;
if(sendto(fds,buf,size,0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("发送成功\n");
ssize_t res=0;
//打开一个文件舒服
int fd=open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
while(1)
{
socklen_t len =sizeof(sin1);
res=recvfrom(fds,(void*)buf,sizeof(buf),0,(struct sockaddr*)&sin1,&len);
if(res<0)
{
ERR_MSG("recvfrom");
return -1;
}
printf("recv success\n");
//组数据包协议
short *p = (short *)buf;
short *p1 =p+1;
char *p2 = buf+4;
write(fd,p2,res-4);
if(res-4<512)
break;
//组ACK
short *pt =(short *)cuf;
*pt = htons(4);
short *pt1 =pt+1;
*pt1 = *p1;
if(sendto(fds,cuf,sizeof(cuf),0,(struct sockaddr*)&sin1,sizeof(sin1))<0)
{
ERR_MSG("sendto");
return -1;
}
}
printf("下载完成\n");
while(1)
sleep(1);
return 0;
}
结果: