connection.c
author Markus Bröker<broeker.markus@googlemail.com>
Fri, 20 Oct 2017 06:41:27 +0200
changeset 168 dfb60716880c
parent 163 780bf4f348f3
permissions -rw-r--r--
Broken OSX Demo added

/**
 * tcpconnect.c
 * Copyright (C) 2010 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <netdb.h>
#include <arpa/inet.h>

#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

int tcpconnect (char *server, char *port)
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;

    int sockfd = -1;

    memset (&hints, 0, sizeof (struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = 0;
    hints.ai_protocol = IPPROTO_TCP;

    if (getaddrinfo (server, port, &hints, &result) != 0) {
        perror ("getaddrinfo");
        return -1;
    }

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        if ((sockfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
            continue;

        if (connect (sockfd, rp->ai_addr, rp->ai_addrlen) != -1) {
            break;
        }
        close (sockfd);
        sockfd = -1;
    }

    if (result != NULL)
        freeaddrinfo (result);

    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)
{
    int sockfd;
    char *result;

    if (argc != 3) {
        printf ("Usage: %s <ipaddr> <service>\n", argv[0]);
        return EXIT_FAILURE;
    }

    if ((sockfd = tcpconnect (argv[1], argv[2])) < 0) {
        printf ("Connection error: %s:%s\n", argv[1], argv[2]);
        return EXIT_FAILURE;
    }

    result = get (sockfd, "/");
    printf ("RESPONSE: %s", result);

    if (result)
        free (result);

    return close (sockfd);
}