基于ftp的服务器下载
#include
#include
#include
#include
#include
#include
#define ERR_MSG(msg) do{\
fprintf(stderr, "\nline:%d: %s %s ", __LINE__, __FILE__, __func__);\
perror("socket");\
}while(0)
#define IP "192.168.2.89" //ifconfig出来的本机ip
#define PORT 69 //1024~49151,网络字节序
#define CLI_PORT 8888
#define CLI_IP "192.168.2.11"
int main(int argc, const char *argv[])
{
//创建报式套接字
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if(cfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("create socket success sfd=%d __%d__\n", cfd, __LINE__);
//填充服务器的地址信息结构体,给sendto函数使用
//sendto函数中,想发给谁,就填谁的地址信息
struct sockaddr_in sin;
sin.sin_family = AF_INET; //必须填AF_INET;
sin.sin_port = htons(PORT); //1024~49151,网络字节序
sin.sin_addr.s_addr = inet_addr(IP);
printf("输入要下载的文件名>>");
char filename[20] = "";
scanf("%s",filename);
getchar();
//组下载请求包
char buf[516] = "";
int size = sprintf(buf,"%c%c%s%c%s%c", 0, 1, filename, 0, "octet", 0);
if(sendto(cfd, buf, size, 0, (struct sockaddr*)&sin,sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("send success __%d__\n",__LINE__);
//打开文件,用于存储数据
int fd = -1;
socklen_t addrlen = sizeof(sin);
ssize_t res = 0;
unsigned short int num = 0;
//接收
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
while(1)
{
bzero(buf,sizeof(buf));
if(recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen) < 0)
{
ERR_MSG("recvfrom");
return -1;
}
//判断是错误包还是数据包
if(3 == buf[1])
{
if(fd < 0)
{
fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0664);
if(fd < 0)
{
ERR_MSG("open");
return -1;
}
}
//判断服务器发送过来的数据包是否是需要的数据包,防止重复收包
if(htons(num+1) == *(unsigned short*)(buf+2))
{
num++;
//将数据存储到文件中,注意最后一次的数据长度小于512
if(write(fd, buf+4, res-4) < 0)
{
ERR_MSG("write");
return -1;
}
//回复ACK包,由于数据包的前四个字节与ACK包只有操作码不一致
//所以只需要修改操作码为4即可
buf[1] = 4;
if(sendto(cfd, buf, 4, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("sendto");
return -1;
}
//若数据小于512,跳出循环
if(res-2-2<512)
{
printf("下载完毕\n");
break;
}
}
}
else if(5 == buf[1]) //错误包
{
printf("download failed:%s\n", buf+4);
break;
}
}
close(fd);
//关闭套接字
close(cfd);
return 0;
}