-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.c
133 lines (110 loc) · 2.66 KB
/
common.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
/**
* Common helper functions for sockchat
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <netdb.h>
#include <errno.h>
#define SERVER_LIST_SIZE 10
#define COORDINATOR_IP "127.0.0.1"
#define COORDINATOR_PORT 10000
#define SERVER_PORT_START 6000
#define SERVERS 10
// ------- String --------
struct string {
unsigned int size;
char *str;
};
typedef struct string string;
struct server_info {
unsigned int ip[4];
int port;
};
typedef struct server_info server_info;
// ------- Function Prototypes --------
void error(char *msg);
string string_create(char *);
string recv_string(int sock);
void send_string(int sock, string str);
void free_string(string str);
void send_forced(int sock, void *buf, size_t size);
void recv_forced(int sock, void *buf, size_t size);
// ------- Generic helper functions --------
void error(char *msg)
{
perror(msg);
exit(1);
}
// helper function to send and receive string structs
string string_create(char *char_vector){
string str;
int len;
len = strlen(char_vector);
if (char_vector[len-1] == '\n') {
char_vector[len-1] = '\0';
len--;
}
str.size = len;
str.str = (char*) malloc(len*sizeof(char));
strcpy(str.str, char_vector);
return str;
}
string recv_string(int sock)
{
string result;
recv_forced(sock, &result.size, sizeof(result.size));
result.str = (char*) malloc((result.size+1)*sizeof(char));
recv_forced(sock, result.str, result.size*sizeof(char));
result.str[result.size] = '\0';
return result;
}
void send_string(int sock, string str)
{
send_forced(sock, &str.size, sizeof(str.size));
send_forced(sock, str.str, str.size*sizeof(char));
}
void free_string(string str)
{
if (str.str != NULL)
{
free(str.str);
}
}
void send_forced(int sock, void *buf, size_t size)
{
size_t transfered;
while (1) {
transfered = send(sock, buf, size, 0);
if (transfered == size) break;
size -= transfered;
buf += transfered;
switch (errno) {
case EAGAIN:
continue;
default:
error("ERROR on send_forced");
}
}
}
void recv_forced(int sock, void *buf, size_t size)
{
size_t transfered;
while (1) {
transfered = recv(sock, buf, size, 0);
if (transfered == size) break;
size -= transfered;
buf += transfered;
switch (errno) {
case EAGAIN:
continue;
default:
error("ERROR on recv_forced");
}
}
}