--- a/connection.c
+++ b/connection.c
@@ -1,7 +1,6 @@
/**
- * connection.c
- * Copyright (C) 2008 mussolini
- * Copyright (C) 2008 mbroeker
+ * tcpconnect.c
+ * Copyright (C) 2010 Markus Broeker
*/
#include <stdio.h>
@@ -16,7 +15,7 @@
#include <sys/types.h>
#include <sys/socket.h>
-int connection (char *server, char *port)
+int tcpconnect (char *server, char *port)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
@@ -51,33 +50,53 @@
return (sockfd);
}
+char *get (int sockfd, const char *path)
+{
+ char *result, *current;
+ char buffer[1024];
+ int len;
+ int i = 1;
+
+ len = sprintf (buffer, "GET %s HTTP/1.0\r\n\r\n", path);
+
+ if (write (sockfd, buffer, len) == -1) {
+ perror ("write");
+ return NULL;
+ }
+
+ result = malloc (1024);
+ while ((len = read (sockfd, buffer, 1023)) > 0) {
+ buffer[len] = '\0';
+ strcat (result, buffer);
+ if ((current = realloc (result, 1024 * ++i)) == NULL) {
+ break;
+ }
+ result = current;
+ }
+
+ return result;
+}
+
int main (int argc, char **argv)
{
- char buffer[1024];
-
int sockfd;
-
- int num;
+ char *result;
if (argc != 3) {
printf ("Usage: %s <ipaddr> <service>\n", argv[0]);
return EXIT_FAILURE;
}
- if ((sockfd = connection (argv[1], argv[2])) < 0) {
+ if ((sockfd = tcpconnect (argv[1], argv[2])) < 0) {
printf ("Connection error: %s:%s\n", argv[1], argv[2]);
return EXIT_FAILURE;
}
- if (write (sockfd, "GET / HTTP/1.0\r\n\r\n", 18) == -1) {
- perror ("write");
- return EXIT_FAILURE;
- }
+ result = get (sockfd, "/");
+ printf ("RESPONSE: %s", result);
- while ((num = read (sockfd, buffer, 1023)) != 0) {
- buffer[num] = 0;
- printf ("%s", buffer);
- }
+ if (result)
+ free (result);
return close (sockfd);
}