onsdag 14. mars 2012

Vortex level0, while still learning C....

I have been playing around with overthewire.org first levels of wargame(s) a few times before. Its a golden opportunity for me now to do them in C.
Althou going over the "C-socket hill" was pretty tough, i finally managed it!

The first one i solved was vortex level0.

I did it a few different ways and ended up with a tidy code (i think):

vortex_level0.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>

#define HOST "vortex.labs.overthewire.org"
#define PORT "5842"

int sockfd();
int connect_host();
int handle_uints();
int get_tze_pass();

int main()
{
    int socket;
    socket = sockfd();
    connect_host(socket);
    handle_uints(socket);
    get_tze_pass(socket);
    close(socket);
    return 0;
}

int sockfd()
{
    return socket(AF_INET, SOCK_STREAM, 0);
}
int connect_host(int socket)
{
    struct addrinfo hostname, *p;
    memset(&hostname, 0, sizeof(hostname));
    hostname.ai_family = AF_INET;
    hostname.ai_socktype = SOCK_STREAM;

    getaddrinfo(HOST,PORT, &hostname, &p);
    connect(socket, p->ai_addr, p->ai_addrlen);
   
    return 0;
}
int handle_uints(int socket)
{
    int uints[4], i, sum = 0;
    for (i = 0; i < 4; i++) {
        read(socket, &uints[i], 4);
    }
    for (i = 0; i < 4; i++) {
        sum = sum + uints[i];
    }
    send(socket, &sum, sizeof(sum), 0);
    return 0;
}
int get_tze_pass(int socket)
{
    char login[18];
    recv(socket, &login, sizeof(login), 0);
    printf("%s\n", login);
    recv(socket, &login, sizeof(login), 0);
    printf("%s\n", login);
    return 0;
}

Ingen kommentarer:

Legg inn en kommentar