PacketReader.cpp
author Markus Bröker <mbroeker@largo.homelinux.org>
Thu, 20 Aug 2009 21:08:16 +0200
changeset 6 acfe33bf1dcc
parent 0 826dd5531eb0
child 8 6097dc1fe2cf
permissions -rw-r--r--
Minimum and Maximum Expanding Error in newer qt versions

/*
 *  $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;
}