-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.c
69 lines (52 loc) · 1.22 KB
/
socket.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
#include "socket.h"
static int sent = 0;
void connect_server(Config *config)
{
SOCKET sock;
printf("connecting ...\n");
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("error creating socket : %s\n", strerror(errno));
exit(1);
}
struct hostent *hostinfo = NULL;
SOCKADDR_IN sin = { 0 };
hostinfo = gethostbyname(config->server);
if (hostinfo == NULL)
{
fprintf (stderr, "Unknown host %s.\n", config->server);
exit(1);
}
sin.sin_addr = *(IN_ADDR *) hostinfo->h_addr;
sin.sin_port = htons(config->port);
sin.sin_family = AF_INET;
if(connect(sock,(SOCKADDR *) &sin, sizeof(SOCKADDR)) == -1)
{
fprintf (stderr, "connect error: %s.\n", strerror(errno));
exit(1);
}
config->socket = sock;
}
int write_server(Config *config, char *str)
{
int n;
log_msg(config, str, 1);
n = write(config->socket, str, strlen(str));
return n;
}
int log_msg(Config *config, char *str, int side) {
int n;
if (!sent) {
if (side == 1) {
write(config->log, ">> ", 3);
} else {
write(config->log, "<< ", 3);
}
sent = 1;
}
n = write(config->log, str, strlen(str));
if (str[0] == '\n') {
sent = 0;
}
return n;
}