-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsender.c
78 lines (61 loc) · 1.96 KB
/
sender.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
#include "gbn.h"
int main(int argc, char *argv[]){
int sockfd; /* socket file descriptor of the client */
int numRead;
socklen_t socklen; /* length of the socket structure sockaddr */
char buf[DATALEN * N]; /* buffer to send packets */
struct hostent *he; /* structure for resolving names into IP addresses */
FILE *inputFile; /* input file pointer */
struct sockaddr_in server;
socklen = sizeof(struct sockaddr);
/*----- Checking arguments -----*/
if (argc != 4){
fprintf(stderr, "usage: sender <hostname> <port> <filename>\n");
exit(-1);
}
/*----- Opening the input file -----*/
if ((inputFile = fopen(argv[3], "rb")) == NULL){
perror("fopen");
exit(-1);
}
/*----- Resolving hostname to the respective IP address -----*/
if ((he = gethostbyname(argv[1])) == NULL){
perror("gethostbyname");
exit(-1);
}
/*----- Opening the socket -----*/
if ((sockfd = gbn_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
perror("gbn_socket");
exit(-1);
}
/*--- Setting the server's parameters -----*/
memset(&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_addr = *(struct in_addr *)he->h_addr;
server.sin_port = htons(atoi(argv[2]));
/*----- Connecting to the server -----*/
if (gbn_connect(sockfd, (struct sockaddr *)&server, socklen) == -1){
perror("gbn_connect");
exit(-1);
}
/*----- Reading from the file and sending it through the socket -----*/
printf("File address\n");
while ((numRead = fread(buf, 1, DATALEN * N, inputFile)) > 0){
printf("numRead: %d, datalen: %d, buffer: %s\n", numRead, DATALEN * N, buf);
if (gbn_send(sockfd, buf, numRead, 0) == -1){
perror("gbn_send");
exit(-1);
}
}
/*----- Closing the socket -----*/
if (gbn_close(sockfd) == -1){
perror("gbn_close");
exit(-1);
}
/*----- Closing the file -----*/
if (fclose(inputFile) == EOF){
perror("fclose");
exit(-1);
}
return(0);
}