-
Notifications
You must be signed in to change notification settings - Fork 0
/
proj1.c
1761 lines (1413 loc) · 36.9 KB
/
proj1.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Project 1: File Sharing System
* Modern Networking Concepts, CSE 589, Spring 2014
* ----------------------------
* @author: Bartlomiej Karmilowicz
* @created: 1st February
*
* HOW-TO: Start of as a Server or Client on specified port
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include <libgen.h>
/* Constants */
#define MAXARGS 8 // the largest is DOWNLOAD up to 7
#define BACKLOG 10 // max queue for listening
#define CHUNK 512 // DEFINE CHUNK SIZE
#define MESSAGE 5000 // Buffer Size for Messages
#define MAXCON 4 // Server + 3 Unique peers
/* tags for SELECT MANAGEMENT; */
#define ADD 1
#define DELETE 2
/* helper tags */
#define CLOSED 1234
/* message codes */
#define REGISTER 5421
#define ADD_IP_LIST 4800
#define SEND_FILE 6991
#define REQUEST_FILE 7653
#define NOTIFICATION 4331
typedef int bool;
#define true 1
#define false 0
/* struct holding all information about this local host. */
struct localHost {
bool isServer; /* value indicating if SERVER || CLIENT */
char ipaddr[INET6_ADDRSTRLEN]; /* IP ADDRESS OF THIS PROCESS */
char port[50]; /* listening port OF THIS PROCESS */
char hostname[250]; /* hostname OF THIS PROCESS */
bool isRegistered;
};
/* struct holding all information about connected peer */
/* used in connections list and Server IP list. */
struct peer {
int socket;
char hostname[250];
char port[50];
char ipaddr[INET6_ADDRSTRLEN];
bool client;
struct peer *next;
};
/* static definitions, used throughout the whole scope of program */
static struct localHost localInfo;
static int serverSocket; /* main listening socket */
static fd_set master_set; /*master file descriptor set*/
static int fdmax = 0; /*max file desc. #*/
static int connectionsCount = 0; /*number of connections for this host*/
/* List of connections established with this host */
struct peer *connections_list;
struct peer *head;
/* UP-TO-DATE copy of Server's IP LIST. */
struct peer *IP_LIST;
struct peer *ip_head;
/* Function declarations */
//Command Functions
void cmd_CutAll();
int cmd_creator();
int cmd_mainmenu();
int cmd_myip();
int cmd_port();
int cmd_exit();
int cmd_download(int argc, char* argv[]);
int cmd_upload(int argc, char* argv[]);
int cmd_connect(int argc, char* argv[]);
int cmd_register(int argc, char* argv[]);
int cmd_list();
int cmd_terminate(int argc, char* argv[]);
//Connections List API
void addToConnections(char *hostName, char *hostPort, char *hostIP, int socketfd);
int removeFromConnections(int socketfd);
int getSocketFromList(int id);
struct peer* findConnection(int socketfd);
int findID(int socketfd);
//Server Ip List API
void DESTROY_IPLIST();
void SAVE_IPLIST(char *hostName, char *hostPort, char *hostIP);
void PRINT_IPLIST();
void sendIPLIST();
//Operations
static int command_execute(char *command);
int handle_command(int socket);
int receiveFile(int socket, char * filename, char * file_len, char * chunks_num);
int acceptConnection();
int setupConnection();
int getHostInfo();
int selector();
int updateSelect(int operation, int socketfd, fd_set* fdset, int* fdmax);
/*
* Method to get the port number
* @arg line struct sockaddr (can be typecasted)
* @return port number
*/
in_port_t get_in_port(struct sockaddr *sa)
{
return (((struct sockaddr_in*)sa)->sin_port);
//printf("port is %d\n",ntohs(get_in_port((struct sockaddr *)p->ai_addr)));
}
/*
* Method to get the port number
* @arg line struct sockaddr (can be typecasted)
* @return pointer to addr field
*/
void *get_in_addr(struct sockaddr *sa)
{
return &(((struct sockaddr_in*)sa)->sin_addr);
}
/*
* Methods ensuring safe sending
* @arg socket, buffer with message, size of buffer
* @return total bytes send
*/
int sendall(int s, char *buf, size_t len){
int total = 0;
int bytesleft = len;
int n;
while(total < len){
n = send(s, buf+total, bytesleft, 0);
//printf("SEND %d\n",n);
if(n == -1){ break; }
total += n;
bytesleft -= n;
}
len = total;
return total;
}
/*
* Methods ensuring safe receive
* @arg socket, buffer with message, size of buffer
* @return total bytes received
*/
int recvall(int s, char *buf, size_t len){
int total = 0;
int bytesleft = len;
int n;
while(total < len){
n = recv(s, buf+total, bytesleft, 0);
//printf("RECEIVED from: %d\n", s);
if(n == -1){ break; }
if(n == 0){ return CLOSED;}
total += n;
bytesleft -= n;
}
len = total;
return total;
}
/************** TIME FUNCTIONS *********************/
/*
* Method returning current time
* @arg void
* @return pointer to buffer with current time
*/
const char * getTime(){
time_t timer;
char buffer[25];
struct tm* time_info;
time(&timer);
time_info = localtime(&timer);
strftime(buffer, 25, "%F %H:%M:%S", time_info);
char *result;
result = malloc(strlen(buffer));
sprintf(result, "%s", buffer);
return result;
}
/*
* Method returning wall clock time
* Used to record point in time (time measurement)
* @arg pointer to struct timeval
* @return wallclock time
*/
double timer(struct timeval *timevalue){
gettimeofday(timevalue, NULL);
return(timevalue->tv_sec + (timevalue->tv_usec / 1000000.0));
}
/************** LISTS MANAGEMENT *********************/
/* API to connection's list and SERVER IP LIST */
/*
* Method adding new connection to connection list
* @arg name of host, port number, ip address, socket
* @return void
*/
void addToConnections(char *hostName, char *hostPort, char *hostIP, int socketfd)
{
printf("Updating connections list..\n");
//create new node
struct peer *lastNode;
lastNode = (struct peer *)malloc(sizeof(struct peer));
//initiliaze node with passed information
strncpy(lastNode->hostname, hostName, sizeof(lastNode->hostname));
strncpy(lastNode->port, hostPort, sizeof(lastNode->port));
strncpy(lastNode->ipaddr, hostIP, sizeof(lastNode->ipaddr));
lastNode->socket = socketfd;
lastNode->next = NULL;
//position the pointers
if(head == NULL){
connections_list = lastNode;
head = connections_list;
}else{
connections_list->next = lastNode;
connections_list = connections_list->next;
}
connectionsCount += 1;
printf("CONNECTION COUNT: %d\n", connectionsCount);
}
/*
* Method removing new connection from connection list
* @arg name of host, port number, ip address, socket
* @return void
*/
int removeFromConnections(int socketfd)
{
printf("Updating connections list..\n");
struct peer *prev = NULL;
struct peer *del = head;
bool found;
//find the connection
while(del != NULL){
if(del->socket == socketfd){
found = true;
break;
}else{
prev = del;
del = del->next;
}
}
if(del == NULL){
printf("No such entry exists, deletion stopped\n");
return -1;
}
//reposition pointers
if(prev != NULL){
prev->next = del->next;
}else if(del == head){
head = del->next;
}
struct peer *tmp = head;
struct peer *newTail = NULL;
while(tmp != NULL){
newTail = tmp;
tmp = tmp->next;
}
connections_list = newTail;
connectionsCount -= 1;
printf("Connection Count: %d\n", connectionsCount);
if(strcmp(del->hostname, "timberlake.cse.buffalo.edu") == 0){
localInfo.isRegistered = false;
cmd_CutAll();
}
//destroy old struct
free(del);
del = NULL;
return 0;
}
/*
* Method to find the connection
* @arg socket
* @return struct peer *
*/
struct peer* findConnection(int socketfd)
{
struct peer *del = head;
bool found = false;
while(del != NULL){
if(del->socket == socketfd){
found = true;
//printf("Found the value\n");
break;
}else{
del = del->next;
}
}
if(found){
return del;
}
return NULL;
}
/*
* Method to find the ID of connection
* @arg socket
* @return ID
*/
int findID(int socketfd)
{
int ID = 1;
bool found = true;
struct peer *del = head;
while(del != NULL){
if(del->socket == socketfd){
found = true;
//printf("Found the value\n");
break;
}else{
del = del->next;
ID += 1;
}
}
if(found){
return ID;
}
return -1;
}
/*
* Method to find the socket from connection ID
* @arg ID of connection
* @return socket
*/
int getSocketFromList(int id)
{
struct peer *del = head;
int result;
int i;
i = 1;
while(i != id){
del = del->next;
i = i + 1;
}
if(del == NULL){
printf("Connection with specified ID does not exist\n");
return EINVAL;
}
if(strcmp(del->hostname, "timberlake.cse.buffalo.edu") == 0){
localInfo.isRegistered = false;
}
result = del->socket;
return result;
}
/*
* Method to destroy current Server Ip List
* @arg void
* @return void
*/
void DESTROY_IPLIST()
{
struct peer *temp;
while(ip_head != NULL){
temp = ip_head;
ip_head = ip_head->next;
free(temp);
}
//reset
ip_head = NULL;
IP_LIST = NULL;
}
/*
* Method to save the entry in Server IP list
* Similiar logic as in Connections List
* @arg host name, host port, host ip address
* @return void
*/
void SAVE_IPLIST(char *hostName, char *hostPort, char *hostIP)
{
struct peer *lastNode;
lastNode = (struct peer *)malloc(sizeof(struct peer));
strncpy(lastNode->hostname, hostName, sizeof(lastNode->hostname));
strncpy(lastNode->port, hostPort, sizeof(lastNode->port));
strncpy(lastNode->ipaddr, hostIP, sizeof(lastNode->ipaddr));
lastNode->next = NULL;
if(ip_head == NULL){
IP_LIST = lastNode;
ip_head = IP_LIST;
}else{
IP_LIST->next = lastNode;
IP_LIST = IP_LIST->next;
}
}
/*
* Method to print out the Server IP list
* @arg void
* @return void
*/
void PRINT_IPLIST(){
struct peer *temp = ip_head;
printf("******************************************************\n");
while(temp != NULL){
printf("%s | %s | %s\n",temp->hostname, temp->ipaddr, temp->port);
temp = temp->next;
}
printf("******************************************************\n");
}
/*
* Method used exclusively by server
* Broadcasts an IP List to all connected hosts
* @arg void
* @return void
*/
void sendIPLIST()
{
if(!localInfo.isServer){
printf("Only Server Boradcasts IP LIST\n");
return;
}
if(head == NULL){
//nothing to send
return;
}
printf("Broadcasting IP LIST to peers..\n");
//buffer that will hold entire connection list from server
char ipList[MESSAGE];
char* scanner = ipList;
int nbytes;
//add message header
nbytes = sprintf(scanner, "%d ", ADD_IP_LIST);
scanner += nbytes;
struct peer *list = head;
while(list != NULL){
nbytes = sprintf(scanner, "%s %s %s ", list->hostname, list->ipaddr, list->port);
scanner += nbytes;
list = list->next;
}
//tag the end of the buffer
sprintf(scanner, "EOF EOF EOF");
//reset pointer over list for sending
list = head;
//send IP LIST buffer to every socket listed
while(list != NULL){
if(sendall(list->socket, ipList, sizeof(ipList)) == -1){
perror("sendIPLIST: send ");
return;
}
list = list->next;
}
}
/*
* MENU AND COMMAND HANDLING SYSTEM
*/
/*
* Command used to print out supported commands on host
* @arg void
* @return void
*/
int cmd_mainmenu()
{
if(!localInfo.isServer){
char *clientmenu =
"\n....................HELP MENU......................\n"
" \n"
"[ MYIP ] Display IP of this process \n"
"[ CREATOR ] Display programmer ID \n"
"[ LIST ] Display current connections \n"
"[ EXIT ] Exit the process \n"
"[ TERMINATE <id> ] Close connection \n"
"[ REGISTER <ip> <localInfo.port> ] Registration on server \n"
"[ CONNECT <ip/localInfo.hostname> <localInfo.port> ] New TCP connection\n"
"[ UPLOAD <id> <file> ] Upload file to host <id> \n"
"[ DOWNLOAD <id> <file> | | ] Download from hosts \n"
"...................................................\n";
printf("%s\n",clientmenu);
}else{
char *servermenu =
"\n....................HELP MENU......................\n"
" \n"
"[ MYIP ] Display IP of this process \n"
"[ CREATOR ] Display programmer ID \n"
"[ LIST ] Display current connections \n"
"[ EXIT ] Exit the process \n"
"[ TERMINATE <id> ] Close connection \n"
"...................................................\n";
printf("%s\n",servermenu);
}
return 0;
}
/*
* Command used to print out IP address
* @arg void
* @return void
*/
int cmd_myip()
{
printf("IP: %s\n", localInfo.ipaddr);
return 0;
}
/*
* Command used to print out port number
* @arg void
* @return void
*/
int cmd_port()
{
printf("PORT: %s\n", localInfo.port);
return 0;
}
/*
* Command used to print out authors information
* @arg void
* @return void
*/
int cmd_creator()
{
char *creator =
"\n======================================\n"
"whoami: bartlomiej karmilowicz \n"
"address: bartlomi@buffalo.edu \n"
"UBITname: bartlomi \n"
"======================================\n";
printf("%s\n", creator);
return 0;
}
/*
* Command used to exit the system
* @arg void
* @return void
*/
int cmd_exit()
{
//cmd_CutAll();
exit(1);
}
/*
* Command used to download files from remote hosts
* @arg argument count, pointer to char * array
* @return 0 success, errno fail
*/
int cmd_download(int argc, char* argv[])
{
//check if eligible for download
if(localInfo.isServer){
printf("Command Not Avaiable on Server\n");
return EINVAL;
}
if(argc < 3){
printf("Peer ID and Filename required\n");
return EINVAL;
}
printf("ARG COUNT %d\n", argc);
if(argc % 2 == 0){
printf("Provide connection ID and fileName for every host\n");
return EINVAL;
}
int index = 1;
char * filename;
int socketfd;
char message[MESSAGE];
//Loop for every pair [ID, FILENAME]
//send request for file to each of listed hosts
while(index < argc){
socketfd = getSocketFromList(atoi(argv[index]));
if(socketfd == EINVAL){
printf("Upload Failed.\n");
return EINVAL;
}
filename = argv[index + 1];
//REQUEST file from remote host
sprintf(message, "%d %s\n", REQUEST_FILE, filename);
if(sendall(socketfd, message, sizeof(message)) == -1){
perror("UPLOAD: message ");
return -1;
}
index += 2;
}
return 0;
}
/*
* Command used to upload file to remote host
* @arg argument count, pointer to char * array
* @return 0 success, errno fail
*/
int cmd_upload(int argc, char* argv[])
{
if(localInfo.isServer){
printf("Command Not Avaiable on Server\n");
return EINVAL;
}
//check arguments size
if(argc < 3){
printf("Peer ID and Filename required\n");
return EINVAL;
}
//get socket ID from list
int socketfd = getSocketFromList(atoi(argv[1]));
if(socketfd == EINVAL){
printf("Upload Failed.\n");
return EINVAL;
}
//declarations
char chunk[CHUNK];
char * filename;
FILE *file;
int numChunks;
int result;
int file_len;
filename = argv[2];
file = fopen (filename,"rb");
if(file == NULL){
perror("FILE: fopen ");
return -1;
}
if ((result = fseek(file, 0, SEEK_END)) != 0){
perror("FILE: fseek ");
return result;
}
//FILE size and number of chunks needed
file_len = ftell(file);
numChunks = file_len / CHUNK;
if(file_len % CHUNK != 0){
numChunks += 1;
}
rewind(file);
//prepare info message for targeted host about file.
//SEND_FILE, FILE_NAME, FILE_SIZE, NumOfChunks
char *bname;
char *filePath = strdup(filename);
bname = basename(filePath);
char sendBuff[MESSAGE];
sprintf(sendBuff, "%d %s %d %d\n", SEND_FILE, bname, file_len, numChunks);
if(sendall(socketfd, sendBuff, sizeof(sendBuff)) == -1){
perror("UPLOAD: message ");
return;
}
int totallyRead = 0;
int readBytes = 0;
int totallySent = 0;
struct timeval t0,t1;
double start, finish;
start = timer(&t0);
while(totallyRead < file_len){
readBytes = fread(chunk, sizeof(char), sizeof(chunk), file);
totallyRead += readBytes;
if((totallySent += sendall(socketfd, chunk, readBytes)) == -1){
perror("UPLOAD: sendingFile ");
return;
}
}
finish = timer(&t1);
fclose(file);
double txRate = (double)(totallySent * 8) / (finish - start);
printf("\n");
printf("***********************************************************\n");
printf("UPLOAD COMPLETED %d%\n", ((totallySent/file_len) * 100));
printf("FILE SIZE: %d Bytes Sent: %d CHUNKS: %d\n", file_len, totallySent, numChunks);
printf("UPLOAD TIME: %fs\n", (finish - start));
printf("UPLOAD RATE Tx: %f bits/s\n", txRate);
printf("***********************************************************\n");
printf("\n");
return 0;
}
/*
* Command used to validate connection
* @arg host name
* @return 0 success, errno fail
*/
int validateConnection(char* HOSTNAME)
{
//check for self connection
if(strcmp(HOSTNAME, localInfo.hostname) == 0){
printf("CONNECTION FAILED: You cannot self connect\n");
return -1;
}
//check if server
if(localInfo.isServer){
printf("Only clients can make connections\n");
return -1;
}
//check if registered
if(!localInfo.isRegistered){
printf("CONNECTION REJECTED: In order to make connections, register on server\n");
return -1;
}
//check if max connection number is met
if(connectionsCount == MAXCON){
printf("No more connections allowed. MAX 4\n");
return -1;
}
//check if already connected
struct peer *scanner = head;
while(scanner != NULL){
if(strcmp(scanner->hostname, HOSTNAME) == 0){
printf("Already Connected to this Peer\n");
return -1;
}
scanner = scanner->next;
}
//validate with SERVER IP LIST
scanner = ip_head;
bool found = false;
while(scanner != NULL){
if(strcmp(scanner->hostname, HOSTNAME) == 0){
found = true;
}
scanner = scanner->next;
}
if(!found){
printf("PEER you are trying to connect is not registered with server. Try later..\n");
return -1;
}
return 0;
}
/*
* Command used to connect to remote host
* @arg argument count, pointer to char * array
* @return 0 success, errno fail
*/
int cmd_connect(int argc, char* argv[]){
//check the arguments number
if(argc != 3){
printf("Please Provide IP Address and Port Of Peer\n");
return EINVAL;
}
struct addrinfo hints, *servinfo;
int result;
int peerConnection;
char ipaddr[INET6_ADDRSTRLEN];
char* peer = argv[1];
//safe PORT copying
int pp = atoi(argv[2]);
char peerPort[50];
sprintf(peerPort, "%d", pp);
//validate if connection allowable
result = validateConnection(peer);
if(result == -1){
return EHOSTUNREACH;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
//Connection process initiated
if((result = getaddrinfo(peer, peerPort, &hints, &servinfo)) < 0){
printf("getaddrinfo error:\n");
return result;
}
if((peerConnection = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) < 0){
perror("connect socket :");
return peerConnection;
}
if(connect(peerConnection, servinfo->ai_addr, servinfo->ai_addrlen) < 0){
perror("connect connect :");
return -1;
}
//printout info message about remote host
inet_ntop(servinfo->ai_family, get_in_addr((struct sockaddr *)servinfo->ai_addr), ipaddr, sizeof(ipaddr));
printf("\nCLIENT CONNECTING TO %s\n", ipaddr);
//prepare message containing listening port number and hostnamt
char sendBuff[200];
sprintf(sendBuff, "%s\n", localInfo.port);
if(sendall(peerConnection, sendBuff, sizeof(sendBuff)) == -1){
perror("Register: send ");
close(peerConnection);
return -1;
}
//update connections list
addToConnections(peer, peerPort, ipaddr, peerConnection);
//update descriptor in FD_SET
updateSelect(ADD, peerConnection, &master_set, &fdmax);
printf("\n");
return 0;
}
/*
* Command used to register host with server
* @arg argument count, pointer to char * array
* @return 0 success, errno fail
*/
int cmd_register(int argc, char* argv[])
{
if(localInfo.isServer){
printf("Only Clients Can Register!\n");
return EOPNOTSUPP;
}
if(argc != 3){
printf("Please Provide IP Address and Port Of Server\n");
return EINVAL;
}
if(localInfo.isRegistered){
printf("Already Registered!\n");
return EACCES;
}
struct addrinfo hints, *servinfo;
int result;
int serverConnection;
char s[INET6_ADDRSTRLEN];
//extract arguments
char* server = argv[1];
//safe PORT copying
int pp = atoi(argv[2]);
char serverPort[50];
sprintf(serverPort, "%d", pp);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if((result = getaddrinfo(server, serverPort, &hints, &servinfo)) < 0){
printf("getaddrinfo error:\n");
return result;
}