PacketReader.cpp
changeset 0 826dd5531eb0
child 8 6097dc1fe2cf
equal deleted inserted replaced
-1:000000000000 0:826dd5531eb0
       
     1 /*
       
     2  *  $Id: PacketReader.cpp 54 2008-01-10 00:24:52Z mbroeker $
       
     3  * $URL: http://localhost/svn/cpp/qMonitor/trunk/PacketReader.cpp $
       
     4  */
       
     5 
       
     6 #include <PacketReader.h>
       
     7 
       
     8 PacketReader::PacketReader (int tm)
       
     9 {
       
    10     timeout = tm;
       
    11 
       
    12     if ((p_socket = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) == -1) {
       
    13         perror ("SocketException");
       
    14         throw std::runtime_error ("SocketException: root access required");
       
    15     }
       
    16 }
       
    17 
       
    18 PacketReader::PacketReader (std::string filename)
       
    19 {
       
    20     if ((p_socket = open (filename.c_str (), O_RDONLY)) == -1) {
       
    21         throw std::runtime_error ("FileException");
       
    22     }
       
    23 
       
    24     timeout = -1;
       
    25 }
       
    26 
       
    27 PacketReader::~PacketReader ()
       
    28 {
       
    29     close (p_socket);
       
    30 }
       
    31 
       
    32 std::string PacketReader::read ()
       
    33 {
       
    34     static char s[IP_MAXPACKET + 1];
       
    35     int c;
       
    36 
       
    37     c =::read (p_socket, s, IP_MAXPACKET);
       
    38     s[c] = 0;
       
    39     return std::string (s, c);
       
    40 }
       
    41 
       
    42 bool PacketReader::ready ()
       
    43 {
       
    44     if (p_socket)
       
    45         return true;
       
    46 
       
    47     return false;
       
    48 }
       
    49 
       
    50 bool PacketReader::dataAvailable ()
       
    51 {
       
    52     pollfd fdin;
       
    53     int event = 1;
       
    54 
       
    55     fdin.fd = p_socket;
       
    56     fdin.events = POLLIN;
       
    57     fdin.revents = 0;
       
    58 
       
    59     if (poll (&fdin, event, timeout) > 0)
       
    60         return true;
       
    61 
       
    62     return false;
       
    63 }