/**********************
receive file
*****************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#define MAXLEN 1024
#define DOWNLOAD_PATH "./download"
struct file_info
{
int size;
char name[32];
};
void usage(void)
{
printf("usage: commad <port> \n");
exit(-1);
}
int main(int argc, char *argv[])
{
int recv_fd = -1;
int file_fd = -1;
int new_fd = -1;
int num = -1;
int ret = -1;
int on = 1;
int left = 0;
struct sockaddr_in self_addr;
struct sockaddr_in peer_addr;
int peer_len = sizeof(peer_addr);
char recv_buf[MAXLEN];
char save_path[128];
if(argc != 2)
usage();
recv_fd = socket(AF_INET, SOCK_STREAM, 0);
if(recv_fd < 0)
{
perror("socket");
exit(1);
}
ret = setsockopt(recv_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(ret < 0)
{
perror("setsockopt");
exit(1);
}
memset(&self_addr, 0 , sizeof(self_addr));
memset(&peer_addr, 0 , sizeof(peer_addr));
self_addr.sin_family = AF_INET;
self_addr.sin_port = htons(atoi(argv[1]));
self_addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(recv_fd, (struct sockaddr *)&self_addr, sizeof(self_addr));
if(ret < 0)
{
perror("bind");
exit(1);
}
listen(recv_fd, 5);
new_fd = accept(recv_fd, (struct sockaddr *)&peer_addr, &peer_len);
struct file_info node;
num = read(new_fd, &node, sizeof(node));
left = ntohl(node.size);
sprintf(save_path, "%s/%s", DOWNLOAD_PATH, node.name);
printf("save_path = %s\n", save_path);
file_fd = open(save_path, O_CREAT | O_APPEND | O_RDWR, 0777);
if(file_fd < 0)
{
perror("open");
exit(1);
}
while(1)
{
num = read(new_fd, recv_buf, MAXLEN);
printf("left = %d, num = %d\n", left, num);
if(left == 0)
break;
write(file_fd, recv_buf, num);
left -= num;
}
close(file_fd);
close(new_fd);
close(recv_fd);
return 0;
}