Using reference for exception catching.
[bpdyndnsd] / src / net_helper.cpp
CommitLineData
6650af14
BS
1/** @file
2 * @brief TcpIpHelper class implementation. This class represents a Helper to easily perform tcp/ip operations.
3 *
4 *
5 *
6 * @copyright Intra2net AG
7 * @license GPLv2
8*/
9
10#include "net_helper.h"
11#include "tcp_service.h"
12
13
14using namespace std;
15
16
17/**
c9d27cb6
BS
18 * Default Constructor.
19 */
20NetHelper::NetHelper()
21 : Log(new Logger())
22{
c3c84086 23 IPServicePtr = IPService::Ptr(new TCPService());
c9d27cb6
BS
24}
25
26
27/**
6650af14
BS
28 * Constructor.
29 * @param _log Logger
6650af14
BS
30 */
31NetHelper::NetHelper( const Logger::Ptr _log )
32 : Log(_log)
33{
c3c84086 34 IPServicePtr = IPService::Ptr(new TCPService());
6650af14
BS
35}
36
37
38/**
39 * Default destructor
40 */
41NetHelper::~NetHelper()
42{
43}
44
45
46/**
47 * Open the connection to the peer.
48 * @return 0 if all is fine, -1 on error.
49 */
50int NetHelper::open_connection(const string& hostname, const string& port)
51{
52 try
53 {
54 IPServicePtr->connect(hostname,port);
55 }
d327e816 56 catch ( boost::system::system_error& boost_exception )
6650af14
BS
57 {
58 ostringstream out;
59 out << "NetHelper::open_connection(): " << boost_exception.what() << " Host: " << hostname << " Port: " << port;
60 Log->print_network_error(out.str());
61 return -1;
62 }
63 return 0;
64}
65
66
67/**
68 * Send the given data
69 * @param data Data to send
70 * @return 0 if all is fine, -1 on error.
71 */
72int NetHelper::send_data(const std::string& data)
73{
74 try
75 {
76 IPServicePtr->write_to_socket(data);
77 }
d327e816 78 catch ( boost::system::system_error& boost_exception )
6650af14
BS
79 {
80 ostringstream out;
81 out << "NetHelper::send_data(): " << boost_exception.what() << " Data to be send: " << data;
82 Log->print_network_error(out.str());
83 return -1;
84 }
85 return 0;
86}
87
88
89/**
90 * Receive all available data from the peer.
91 * @return The data received.
92 */
93std::string NetHelper::receive_data()
94{
95 string received_data;
96 try
97 {
98 received_data = IPServicePtr->read_from_socket();
99 }
d327e816 100 catch ( boost::system::system_error& boost_exception )
6650af14
BS
101 {
102 ostringstream out;
103 out << "NetHelper::receive_data(): " << boost_exception.what();
104 Log->print_network_error(out.str());
105 return "";
106 }
107 return received_data;
108}
109
110
111/**
112 * Close the active session.
113 * @return 0 if all is fine, -1 on error
114 */
115int NetHelper::close_connection()
116{
117 try
118 {
119 IPServicePtr->close();
120 }
d327e816 121 catch ( boost::system::system_error& boost_exception )
6650af14
BS
122 {
123 ostringstream out;
124 out << "NetHelper::close_connection(): " << boost_exception.what();
125 Log->print_network_error(out.str());
126 return -1;
127 }
128 return 0;
129}