#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<fcntl.h>
#include<netinet/ip.h>
#include<sys/stat.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, " __%d__ ", __LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
if(argc < 3)
{
fprintf(stderr, "请输入IP port\n");
return -1;
}
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(69);
sin.sin_addr.s_addr = inet_addr(argv[1]);
char buf[600]={0};
char _ack[4];
short code;
short num;
char text[512]={0};
int n=0;
int fd;
char filename[32] = {0};
printf("下载文件名: ");
scanf("%s", filename);
char*ptr=buf;
short int*pa=(short int*)ptr;
*pa=htons(1);
char* pb=ptr+2;
strcpy(pb,filename);
char* pc=pb+strlen(pb);
char* pd=pc+1;
strcpy(pd,"octet");
int size=2+strlen(pb)+1+strlen("octet")+1;
struct sockaddr_in rcv_addrmsg;
socklen_t addrlen = sizeof(rcv_addrmsg);
if(sendto(sfd, buf, size, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto success\n");
while(1)
{
bzero(buf, sizeof(buf));
if((size=recvfrom(sfd, buf, 516, 0, (struct sockaddr*)&rcv_addrmsg, &addrlen)) < 0)
{
ERR_MSG("recvfrom");
return -1;
}
code=ntohs(*(short*)buf);
num=ntohs(*(short*)(buf+2));
printf("%d",num);
if (3 == code && num == n+1)
{
n++;
if (num == 1)
{
if (( fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664))<0)
{
ERR_MSG("open ");
}
printf("open success\n");
}
if (write(fd, buf+4, size - 4)<0)
{
ERR_MSG("write");
}
printf("write success\n");
*(short *)_ack = htons(4);
*(short *)(_ack + 2) = htons(num);
if (sendto(sfd, _ack, 4, 0, (struct sockaddr *)&rcv_addrmsg,addrlen)<0)
{
ERR_MSG("sendto");
}
if (size < 512)
break;
}
else if (code==5)
{
printf("接收出错[%s]\n", text);
}
}
close(sfd);
return 0;
}