14 |
13 |
15 #include <netinet/in.h> |
14 #include <netinet/in.h> |
16 #include <sys/types.h> |
15 #include <sys/types.h> |
17 #include <sys/socket.h> |
16 #include <sys/socket.h> |
18 |
17 |
19 int connection (char *server, char *port) |
18 int tcpconnect (char *server, char *port) |
20 { |
19 { |
21 struct addrinfo hints; |
20 struct addrinfo hints; |
22 struct addrinfo *result, *rp; |
21 struct addrinfo *result, *rp; |
23 |
22 |
24 int sockfd = -1; |
23 int sockfd = -1; |
49 freeaddrinfo (result); |
48 freeaddrinfo (result); |
50 |
49 |
51 return (sockfd); |
50 return (sockfd); |
52 } |
51 } |
53 |
52 |
|
53 char *get (int sockfd, const char *path) |
|
54 { |
|
55 char *result, *current; |
|
56 char buffer[1024]; |
|
57 int len; |
|
58 int i = 1; |
|
59 |
|
60 len = sprintf (buffer, "GET %s HTTP/1.0\r\n\r\n", path); |
|
61 |
|
62 if (write (sockfd, buffer, len) == -1) { |
|
63 perror ("write"); |
|
64 return NULL; |
|
65 } |
|
66 |
|
67 result = malloc (1024); |
|
68 while ((len = read (sockfd, buffer, 1023)) > 0) { |
|
69 buffer[len] = '\0'; |
|
70 strcat (result, buffer); |
|
71 if ((current = realloc (result, 1024 * ++i)) == NULL) { |
|
72 break; |
|
73 } |
|
74 result = current; |
|
75 } |
|
76 |
|
77 return result; |
|
78 } |
|
79 |
54 int main (int argc, char **argv) |
80 int main (int argc, char **argv) |
55 { |
81 { |
56 char buffer[1024]; |
|
57 |
|
58 int sockfd; |
82 int sockfd; |
59 |
83 char *result; |
60 int num; |
|
61 |
84 |
62 if (argc != 3) { |
85 if (argc != 3) { |
63 printf ("Usage: %s <ipaddr> <service>\n", argv[0]); |
86 printf ("Usage: %s <ipaddr> <service>\n", argv[0]); |
64 return EXIT_FAILURE; |
87 return EXIT_FAILURE; |
65 } |
88 } |
66 |
89 |
67 if ((sockfd = connection (argv[1], argv[2])) < 0) { |
90 if ((sockfd = tcpconnect (argv[1], argv[2])) < 0) { |
68 printf ("Connection error: %s:%s\n", argv[1], argv[2]); |
91 printf ("Connection error: %s:%s\n", argv[1], argv[2]); |
69 return EXIT_FAILURE; |
92 return EXIT_FAILURE; |
70 } |
93 } |
71 |
94 |
72 if (write (sockfd, "GET / HTTP/1.0\r\n\r\n", 18) == -1) { |
95 result = get (sockfd, "/"); |
73 perror ("write"); |
96 printf ("RESPONSE: %s", result); |
74 return EXIT_FAILURE; |
|
75 } |
|
76 |
97 |
77 while ((num = read (sockfd, buffer, 1023)) != 0) { |
98 if (result) |
78 buffer[num] = 0; |
99 free (result); |
79 printf ("%s", buffer); |
|
80 } |
|
81 |
100 |
82 return close (sockfd); |
101 return close (sockfd); |
83 } |
102 } |