UDP下载
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "line:%d\n", __LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.8.238" //填你们自己的本机IP ifconfig查看
#define PORT 69 //1024~49151
int main(int argc, const char *argv[])
{
//创建报式套接字
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//填充服务器自身的地址信息结构体,AF_INET: man 7 IP
//供于下方的sendto使用,因为sendto必须要指明发给谁
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
char buf[128] = "";
short* p1=(short*)buf;
*p1=htons(1);
char* p2=buf+2;
strcpy(p2,"5.png");
char* p3=p2+strlen(p2);
*p3=0;
char* p4=p3+1;
strcpy(p4,"octet");
int size=2+strlen(p2)+1+strlen(p4)+1;
if(sendto(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto success\n");
int fd=open(p2,O_WRONLY|O_CREAT|O_TRUNC,0664);
int res;
while(1)
{
char buf1[600]="";
struct sockaddr_in cin; //存储接收到的数据包的地址信息
socklen_t addrlen = sizeof(cin);
if((res=recvfrom(sfd,buf1,sizeof(buf1),0,(struct sockaddr*)&cin,&addrlen))<0)
{
ERR_MSG("recvfrom");
return -1;
}
write(fd,buf1+4,res-4);
short *c1=(short*)buf1;
*c1=htons(4);
if((sendto(sfd,buf1,4,0,(struct sockaddr*)&cin,sizeof(cin)))<0)
{
ERR_MSG("sendto");
return -1;
}
if(res<516)
{
printf("下载完成\n");
break;
}
}
//关闭套接字
close(sfd);
return 0;
}
结果