98 lines
1.9 KiB
C++
98 lines
1.9 KiB
C++
#include "outputudpsocket.hh"
|
|
#include "request.hh"
|
|
#include "resultlist.hh"
|
|
#include "posexcept.hh"
|
|
|
|
#include <owlps.h>
|
|
|
|
#include <sstream>
|
|
#include <cstdio> // For perror()
|
|
|
|
using namespace std ;
|
|
|
|
|
|
|
|
/* *** Constructors *** */
|
|
|
|
|
|
OutputUDPSocket::OutputUDPSocket(const string &_remote_host,
|
|
const uint_fast16_t _remote_port):
|
|
remote_host(_remote_host), remote_port(_remote_port)
|
|
{
|
|
if (! init_socket())
|
|
throw error_opening_output_file("UDP socket") ;
|
|
|
|
}
|
|
|
|
|
|
OutputUDPSocket::~OutputUDPSocket()
|
|
{
|
|
close_socket() ;
|
|
}
|
|
|
|
|
|
|
|
/* *** Operations *** */
|
|
|
|
|
|
/**
|
|
* @return \em true if the socket were successfully opened.
|
|
* @return \em false in case of error.
|
|
*/
|
|
bool OutputUDPSocket::init_socket()
|
|
{
|
|
sockfd = owl_create_udp_trx_socket(remote_host.c_str(), remote_port,
|
|
&server_info, &client_info) ;
|
|
return sockfd >= 0 ;
|
|
}
|
|
|
|
|
|
/**
|
|
* Normally, the socket is closed automatically by the destructor. Use
|
|
* this if you want to close the socket prematurely.
|
|
* #sockfd is set to -1, even in case of error.
|
|
* @return \em true if the socket were successfully closed or were not
|
|
* opened.
|
|
* @return \em false in case of error.
|
|
*/
|
|
bool OutputUDPSocket::close_socket()
|
|
{
|
|
if (sockfd >= 0)
|
|
{
|
|
if (close(sockfd))
|
|
{
|
|
perror("Cannot close UDP socket") ;
|
|
return false ;
|
|
}
|
|
|
|
sockfd = -1 ;
|
|
}
|
|
|
|
return true ;
|
|
}
|
|
|
|
|
|
void OutputUDPSocket::write(const Result &result)
|
|
{
|
|
send_data(result.to_csv()) ;
|
|
}
|
|
|
|
|
|
void OutputUDPSocket::write(const ResultList &results)
|
|
{
|
|
send_data(results.to_csv()) ;
|
|
}
|
|
|
|
|
|
/**
|
|
* Sends the text buffer 'data'.
|
|
*/
|
|
void OutputUDPSocket::send_data(const string &data)
|
|
{
|
|
ssize_t nsent = sendto(sockfd, data.c_str(), data.size(), 0,
|
|
(struct sockaddr *) &server_info,
|
|
sizeof(server_info)) ;
|
|
if (nsent != static_cast<ssize_t>(data.size()))
|
|
perror("Error sending result data") ;
|
|
}
|