connection.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:50:39 +0200
changeset 75 a2c32869d4d5
parent 48 b94d657a9acb
child 77 49e0babccb23
permissions -rw-r--r--
clplaner added clplaner reads a file and draws the knockout stage FILE FORMAT: * One team per line, seperated by newline * team n is the group winner, team n+1 the runners up committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * test/demos/connection.c
 * Copyright (C) 2008 mussolini
 * Copyright (C) 2008 mbroeker
 */

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

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

int connection (char *ip, unsigned short port)
{
    struct hostent *hs;
    struct sockaddr_in sock;

    int sockfd;

    memset (&sock, 0, sizeof (sock));
    sock.sin_family = AF_INET;
    sock.sin_port = htons (port);

    if ((sock.sin_addr.s_addr = inet_addr (ip)) == -1) {
        if ((hs = gethostbyname (ip)) == NULL) {
            perror ("[-] Error");
            return -1;
        }
        sock.sin_family = hs->h_addrtype;
        memcpy (&sock.sin_addr.s_addr, hs->h_addr, hs->h_length);
    }

    if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
        perror ("[-] Error");
        return -1;
    }

    if (connect (sockfd, (struct sockaddr *)&sock, sizeof (sock)) < 0) {
        perror ("[-] Error ");
        return -1;
    }

    return (sockfd);
}

int main (int argc, char **argv)
{
    char buffer[1024];

    int sockfd;

    int num;

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

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

    write (sockfd, "GET /\r\n", 7);

    while ((num = read (sockfd, buffer, 1023)) != 0) {
        buffer[num] = 0;
        printf ("%s", buffer);
    }

    return close (sockfd);
}