代码
#include "heard.h"
#define PORT 69 //端口号的网络字节序 1024~49151
#define IP "192.168.10.122"//ifconfig查看本机IP
int main(int argc, const char *argv[])
{
//创建UDP套接字
int cfd=socket(AF_INET,SOCK_DGRAM,0);
if(cfd<0){
ERR_MSG("socket");
return -1;
}
printf("socket success\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]="";
short*ptr1=(short*)buf;//下载请求1
*ptr1=htons(1);
char*ptr2=buf+2;//文件名
strcpy(ptr2,"5.png");
char*ptr3=ptr2+strlen(ptr2)+1;
strcpy(ptr3,"octet");//模式
int size=4+strlen(ptr2)+strlen(ptr3);
//向服务器发送下载请求
ssize_t ret=sendto(cfd,buf,size,0,(struct sockaddr*)&sin,sizeof(sin));
if(ret<0){
ERR_MSG("sendto");
return -1;
}
printf("请求成功\n");
int i=1;
ssize_t res=0,ack=0;
struct sockaddr_in cin;
socklen_t len=sizeof(cin);
int fd=open("./5.png",O_RDWR|O_CREAT|O_TRUNC,0777);
while(1){
bzero(buf,sizeof(buf));
short*str1=(short*)buf;
short*str2=(short*)buf+1;
char *str3=buf+4;
res=recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&len);
if(res<0){
ERR_MSG("recvfrom");
return -1;
}
printf("%d str2=%d\n",ntohs(*str1),ntohs(*str2)) ;
short a=ntohs(*str1);
if(a==5){
printf("%d ERROR:%s\n",ntohs(*str2),str3);
return -1;
}
write(fd,str3,res-4);
*str1=htons(4);
bzero(str3,512);
printf("%d tr3=%dsizebuf=l%ld\n",ntohs(*str1),ntohs (*str2),sizeof(buf));
ack=sendto(cfd,buf,4,0,(struct sockaddr*)&cin,sizeof(cin));
if(ack<0){
ERR_MSG("sendto");
return -1;
}
if(res<516){
break;
}
}
#if 0
char buf[128]="";
struct sockaddr_in cin;
socklen_t len=sizeof(cin);
while(1){
//发送数据
bzero(buf,sizeof(buf));
printf("请输入 :");
fgets(buf,sizeof(buf),stdin);
ssize_t ret=sendto(cfd,buf,sizeof(buf),0,(struct sockaddr *)&sin,sizeof(sin));
if(ret<0){
ERR_MSG("sendto");
return -1;
}
printf("发送成功\n");
printf("[%s:%d]:%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf);
//接收数据
bzero(buf,sizeof(buf));
ssize_t res=recvfrom(cfd,buf,sizeof(buf),0,(struct sockaddr *)&cin,&len);
if(res<0){
ERR_MSG("recvfrom");
return -1;
}
printf("接收成功\n");
printf("[%s: %d]: %s\n",inet_ntoa(sin.sin_addr),ntohs(sin.sin_port),buf);
}
#endif
//关闭文件描述符
close(cfd);
return 0;
}
实现结果