-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_transfer_function.c
More file actions
83 lines (71 loc) · 1.91 KB
/
Copy pathfile_transfer_function.c
File metadata and controls
83 lines (71 loc) · 1.91 KB
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
/*
* Function: the implementation of file transfer
*
* Author : Daniel Lai
* Created On: 2014-02-21
*/
#include <file_transfer_function.h>
static size_t size_packet = sizeof(struct packet);
void send_EOT(struct packet* hp, struct packet* data, int sfd)
{
int x;
hp->type = EOT;
data = htonp(hp);
if((x = send(sfd, data, size_packet, 0)) != size_packet)
er("send()", x);
}
void send_TERM(struct packet* hp, struct packet* data, int sfd)
{
int x;
hp->type = TERM;
data = htonp(hp);
if((x = send(sfd, data, size_packet, 0)) != size_packet)
er("send()", x);
}
void send_file(struct packet* hp, struct packet* data, int sfd, FILE* f)
{
int x;
int i = 0, j = 0;
while(!feof(f))
{
memset(hp->buffer, '\0', sizeof(char) * LENBUFFER);
hp->datalen = fread(hp->buffer, 1, LENBUFFER - 1, f);
i += hp->datalen;
printpacket(hp, HP);
data = htonp(hp);
if((x = send(sfd, data, size_packet, 0)) != size_packet)
er("send()", x);
j++;
}
fprintf(stderr, "\t%d byte(s) read.\n", i);
fprintf(stderr, "\t%d data packet(s) sent.\n", j);
fflush(stderr);
}
void receive_file(struct packet* hp, struct packet* data, int sfd, FILE* f)
{
int x;
int i = 0, j = 0;
if((x = recv(sfd, data, size_packet, 0)) <= 0)
er("recv()", x);
j++;
hp = ntohp(data);
while(hp->type == DATA)
{
i += fwrite(hp->buffer, 1, hp->datalen, f);
if((x = recv(sfd, data, size_packet, 0)) <= 0)
er("recv()", x);
j++;
hp = ntohp(data);
printpacket(hp, HP);
}
fprintf(stderr, "\t%d data packet(s) received.\n", --j);
fprintf(stderr, "\t%d byte(s) written.\n", i);
if(hp->type == EOT)
return;
else
{
fprintf(stderr, "Error occured while downloading remote file. \n");
exit(2);
}
fflush(stderr);
}