-
Notifications
You must be signed in to change notification settings - Fork 14
/
serverfiletransfer.c
95 lines (82 loc) · 2.13 KB
/
serverfiletransfer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MAX_LINE 2048
#define BUFFSIZE 2048
void writefile(int sockfd, FILE *fp);
ssize_t total=0;
int main(int argc, char *argv[])
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
perror("Can't allocate sockfd");
exit(1);
}
struct sockaddr_in clientaddr, serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(atoi(argv[2]));
if (bind(sockfd, (const struct sockaddr *) &serveraddr, sizeof(serveraddr)) == -1)
{
perror("Bind Error");
exit(1);
}
if (listen(sockfd, argv[2]) == -1)
{
perror("Listen Error");
exit(1);
}
socklen_t addrlen = sizeof(clientaddr);
int connfd = accept(sockfd, (struct sockaddr *) &clientaddr, &addrlen);
if (connfd == -1)
{
perror("Connect Error");
exit(1);
}
close(sockfd);
char filename[BUFFSIZE] = {0};
if (recv(connfd, filename, BUFFSIZE, 0) == -1)
{
perror("Can't receive filename");
exit(1);
}
FILE *fp = fopen(filename, "wb");
if (fp == NULL)
{
perror("Can't open file");
exit(1);
}
char addr[INET_ADDRSTRLEN];
printf("Start receive file: %s from %s\n", filename, inet_ntop(AF_INET, &clientaddr.sin_addr, addr, INET_ADDRSTRLEN));
writefile(connfd, fp);
printf("Receive Success, NumBytes = %ld\n", total);
fclose(fp);
close(connfd);
return 0;
}
void writefile(int sockfd, FILE *fp)
{
ssize_t n;
char buff[MAX_LINE] = {0};
while ((n = recv(sockfd, buff, MAX_LINE, 0)) > 0)
{
total+=n;
if (n == -1)
{
perror("Receive File Error");
exit(1);
}
if (fwrite(buff, sizeof(char), n, fp) != n)
{
perror("Write File Error");
exit(1);
}
memset(buff, 0, MAX_LINE);
}
}