hlswmaster-ng/netpkt.cpp

81 lines
1.5 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 "module.h"
#include "netpkt.h"
NetPkt::NetPkt(int size)
:size(size)
{
data = new char[size];
}
NetPkt::~NetPkt()
{
delete data;
}
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;
if (ioctl(fd, FIONREAD, &recvsize) == -1) {
LogSystem::log(LOG_ERROR, "NetPkt::createFromSocket()");
return NULL;
}
NetPkt* retval = new NetPkt(recvsize);
retval->readFromSocket(fd);
return retval;
}
int NetPkt::checkPortArray(struct game_ports* portarr)
{
int myport = ntohs(this->addr.sin_port);
while (portarr && portarr->portlo) {
int port;
for (port = portarr->portlo; port <= portarr->porthi; port++)
if (port == myport)
return portarr->gameid;
portarr++;
}
return 0;
}
bool NetPkt::compare(int offset, const char* buf, int len)
{
if (offset >= this->size)
return false;
/* nicht ueber das paket hinaus vergleichen */
if (offset + len >= this->size)
len = this->size - offset;
return (memcmp(this->data + offset, buf, len) == 0);
}