56 lines
1.0 KiB
C++
56 lines
1.0 KiB
C++
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <unistd.h>
|
||
|
#include <string.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <sys/ioctl.h>
|
||
|
#include <net/if.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <arpa/inet.h>
|
||
|
|
||
|
#include "logging.h"
|
||
|
#include "netpkt.h"
|
||
|
|
||
|
NetPkt::NetPkt(int size)
|
||
|
:size(size)
|
||
|
{
|
||
|
LogSystem::log(LOG_DEBUG, "NetPkt()");
|
||
|
data = (char*)malloc(size);
|
||
|
}
|
||
|
|
||
|
NetPkt::~NetPkt()
|
||
|
{
|
||
|
free(data);
|
||
|
LogSystem::log(LOG_DEBUG, "~NetPkt()");
|
||
|
}
|
||
|
|
||
|
int NetPkt::readFromSocket(int fd)
|
||
|
{
|
||
|
socklen_t i = sizeof(struct sockaddr_in);
|
||
|
return recvfrom(fd, this->data, this->size, 0, (struct sockaddr *)&this->addr, &i);
|
||
|
}
|
||
|
|
||
|
int NetPkt::show(char* buf, int size)
|
||
|
{
|
||
|
return snprintf(buf, size, "(%s:%d) %d bytes",
|
||
|
inet_ntoa(this->addr.sin_addr),
|
||
|
ntohs(this->addr.sin_port),
|
||
|
this->size);
|
||
|
}
|
||
|
|
||
|
NetPkt* NetPkt::createFromSocket(int fd)
|
||
|
{
|
||
|
int recvsize = 0;
|
||
|
|
||
|
if (ioctl(fd, FIONREAD, &recvsize) == -1) {
|
||
|
LogSystem::log(LOG_WARNING, "NetPkt::createFromSocket()");
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
NetPkt* retval = new NetPkt(recvsize);
|
||
|
retval->readFromSocket(fd);
|
||
|
|
||
|
return retval;
|
||
|
}
|