-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
145 lines (113 loc) · 2.41 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
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
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <sys/select.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#define WRITE_BUFFER_SIZE 1000000
int main (int argc, char **argv)
{
int error = EXIT_SUCCESS;
int ret;
fd_set writeFds, fds, readFds, rfds;
int maxFd;
uint8_t *writeBuffer = NULL;
int connection = -1;
struct sockaddr_in addr;
struct addrinfo hints, *addresses, *currentAddress;
if (argc != 2)
{
printf ("usage: %s <host>\n", argv[0]);
goto END;
}
writeBuffer = malloc (WRITE_BUFFER_SIZE);
if (!writeBuffer)
{
perror ("couldn't allocate memory\n");
error = EXIT_FAILURE;
goto END;
}
memset (writeBuffer, 0, WRITE_BUFFER_SIZE);
connection = socket (AF_INET, SOCK_STREAM, 0);
if (connection < 0)
{
perror ("couldn't create socket");
error = EXIT_FAILURE;
goto END;
}
memset (&addr, 0, sizeof (addr));
memset (&hints, 0, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((ret = getaddrinfo (argv[1], "10001", &hints, &addresses) == 0))
{
currentAddress = addresses;
while (currentAddress)
{
if (connect (connection, currentAddress->ai_addr, sizeof (struct sockaddr)) == 0)
{
ret = 1;
break;
}
currentAddress = currentAddress->ai_next;
}
freeaddrinfo (addresses);
if (ret != 1)
{
perror ("couldn't connect to host");
error = EXIT_FAILURE;
goto END;
}
}
else
{
fprintf (stderr, "getaddrinfo returned %d: %s\n", ret, gai_strerror (ret));
error = EXIT_FAILURE;
goto END;
}
FD_ZERO (&fds);
FD_SET (connection, &fds);
FD_ZERO (&rfds);
FD_SET (STDIN_FILENO, &rfds);
writeFds = fds;
readFds = rfds;
maxFd = STDIN_FILENO;
if (connection > STDIN_FILENO)
maxFd = connection;
printf ("now writing to host, quit with 'q'\n");
while (select (maxFd + 1, &rfds, &fds, NULL, NULL) > 0)
{
if (FD_ISSET (connection, &fds))
{
if (write (connection, writeBuffer, WRITE_BUFFER_SIZE) <= 0)
{
perror ("couldn't write to socket\n");
error = EXIT_FAILURE;
goto END;
}
}
if (FD_ISSET (STDIN_FILENO, &rfds))
{
if (getchar () == 'q')
{
getchar ();
break;
}
getchar ();
}
fds = writeFds;
rfds = readFds;
}
END:
if (connection >= 0)
close (connection);
if (writeBuffer)
free (writeBuffer);
return error;
}