9 #include <unistd.h> |
9 #include <unistd.h> |
10 #include <sys/socket.h> |
10 #include <sys/socket.h> |
11 #include <netinet/in.h> |
11 #include <netinet/in.h> |
12 #include <arpa/inet.h> |
12 #include <arpa/inet.h> |
13 #include <sys/types.h> |
13 #include <sys/types.h> |
|
14 #include <netdb.h> |
|
15 |
|
16 #define MAXLEN 80 |
|
17 |
|
18 int client_write (int client_socket, char *s) |
|
19 { |
|
20 return write (client_socket, s, strlen (s)); |
|
21 } |
14 |
22 |
15 int main (int argc, char **argv) |
23 int main (int argc, char **argv) |
16 { |
24 { |
17 char message[81]; |
25 char message[MAXLEN + 1]; |
18 int client_socket; |
26 int client_socket; |
19 struct sockaddr_in ca; |
|
20 socklen_t size; |
|
21 int status; |
27 int status; |
22 |
28 |
23 client_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); |
29 struct addrinfo hints, *result, *rp; |
24 if (client_socket == -1) { |
30 |
25 perror ("socket"); |
31 memset (&hints, 0, sizeof (struct addrinfo)); |
26 return EXIT_FAILURE; |
32 hints.ai_family = AF_UNSPEC; |
|
33 hints.ai_socktype = SOCK_STREAM; |
|
34 hints.ai_flags = 0; |
|
35 hints.ai_protocol = IPPROTO_TCP; |
|
36 |
|
37 if (getaddrinfo ("localhost", "4000", &hints, &result) != 0) { |
|
38 perror ("getaddrinfo"); |
|
39 return -1; |
27 } |
40 } |
28 |
41 |
29 ca.sin_family = AF_INET; |
42 client_socket = -1; |
30 ca.sin_port = htons (4000); |
43 for (rp = result; rp != NULL; rp = rp->ai_next) { |
31 ca.sin_addr.s_addr = inet_addr ("127.0.0.1"); |
44 if ((client_socket = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1) |
|
45 continue; |
32 |
46 |
33 size = sizeof (ca); |
47 if (connect (client_socket, rp->ai_addr, rp->ai_addrlen) != -1) { |
|
48 break; |
|
49 } |
|
50 close (client_socket); |
|
51 client_socket = -1; |
|
52 } |
34 |
53 |
35 status = connect (client_socket, (struct sockaddr *)&ca, size); |
54 if (result != NULL) |
36 status = write (client_socket, "Hello\r\n", 8); |
55 freeaddrinfo (result); |
|
56 |
|
57 status = client_write (client_socket, "Hello\r\n"); |
37 while (client_socket > 0) { |
58 while (client_socket > 0) { |
38 status = read (client_socket, message, 80); |
59 status = read (client_socket, message, MAXLEN); |
39 if (status > 0) { |
60 if (status > 0) { |
40 message[status] = 0; |
61 message[status] = '\0'; |
41 printf ("SERVER RESPONS: %s", message); |
62 printf ("SERVER RESPONS: %s", message); |
42 } else { |
63 } else { |
43 perror ("READ"); |
64 perror ("READ"); |
44 close (client_socket); |
65 close (client_socket); |
45 return 1; |
66 return 1; |