PacketReader.cpp
author Markus Bröker <mbroeker@largo.homelinux.org>
Sat, 03 Jan 2009 01:28:28 +0100
changeset 4 fdf04a93faeb
parent 0 826dd5531eb0
child 8 6097dc1fe2cf
permissions -rw-r--r--
Codebase indented by me and gnu-indent

/*
 *  $Id: PacketReader.cpp 54 2008-01-10 00:24:52Z mbroeker $
 * $URL: http://localhost/svn/cpp/qMonitor/trunk/PacketReader.cpp $
 */

#include <PacketReader.h>

PacketReader::PacketReader (int tm)
{
    timeout = tm;

    if ((p_socket = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) == -1) {
        perror ("SocketException");
        throw std::runtime_error ("SocketException: root access required");
    }
}

PacketReader::PacketReader (std::string filename)
{
    if ((p_socket = open (filename.c_str (), O_RDONLY)) == -1) {
        throw std::runtime_error ("FileException");
    }

    timeout = -1;
}

PacketReader::~PacketReader ()
{
    close (p_socket);
}

std::string PacketReader::read ()
{
    static char s[IP_MAXPACKET + 1];
    int c;

    c =::read (p_socket, s, IP_MAXPACKET);
    s[c] = 0;
    return std::string (s, c);
}

bool PacketReader::ready ()
{
    if (p_socket)
        return true;

    return false;
}

bool PacketReader::dataAvailable ()
{
    pollfd fdin;
    int event = 1;

    fdin.fd = p_socket;
    fdin.events = POLLIN;
    fdin.revents = 0;

    if (poll (&fdin, event, timeout) > 0)
        return true;

    return false;
}