-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.c
102 lines (83 loc) · 2.54 KB
/
client.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
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <poll.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <netdb.h>
#include <sys/signal.h>
#define CLIENT_NUMBER 510
bool connectionAlive = false;
static void sig_usr(int signo){
if (signo == SIGPIPE){
connectionAlive = false;
}
}
int main(int argc, char* argv[]){
if (sigset(SIGPIPE, sig_usr) == SIG_ERR){
perror("failed to handle SIGPIPE");
exit(1);
}
in_port_t destinationPort;
if (argc == 2){
destinationPort = (in_port_t)atoi(argv[1]);
} else {
printf("Incorrect arguments, client was initialized on default port 1888\n");
destinationPort = 1888;
}
struct sockaddr_in DestinationAddress;
memset(&DestinationAddress, 0 , sizeof(struct sockaddr_in));
DestinationAddress.sin_family = AF_INET;
DestinationAddress.sin_port = htons(destinationPort);
struct in_addr HostAddress = *(struct in_addr*)gethostbyname("localhost")->h_addr_list[0];
memcpy(&DestinationAddress.sin_addr, &HostAddress, sizeof(struct in_addr));
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket");
return -1;
}
if (connect(sock, (struct sockaddr* )&DestinationAddress, sizeof(struct sockaddr_in)) == -1){
perror("connection error");
close(sock);
return -1;
} else {
printf("connected\n");
connectionAlive = true;
}
char readWriteBuf[BUFSIZ];
char tempBuf[BUFSIZ];
int readCount;
int writeCount;
while ((readCount = read(STDIN_FILENO, readWriteBuf, BUFSIZ)) > 0){
if (!connectionAlive){
close(sock);
printf("connection was closed\n");
return 0;
}
while ((writeCount = write(sock, readWriteBuf, readCount)) < readCount){
strncpy(tempBuf, readWriteBuf + writeCount, readCount - writeCount);
memset(&readWriteBuf, 0, sizeof(readWriteBuf));
strncpy(readWriteBuf, tempBuf, readCount - writeCount);
memset(&tempBuf, 0, sizeof(tempBuf));
readCount -= writeCount;
}
if (writeCount == 0){
printf("connection was closed\n");
close(sock);
return 0;
}
if (writeCount == -1){
perror("writing error");
return -1;
}
}
if (readCount == -1){
perror("reading error");
return -1;
}
close(sock);
return 0;
}