libsocket  1.5
Network::UdpSocket Class Reference

This class represent a udp connection (client and server) More...

#include <udpsocket.hh>

Inheritance diagram for Network::UdpSocket:
Network::NetSocket Network::Socket

Public Member Functions

 UdpSocket (SOCKET_VERSION version=V4)
 
 UdpSocket (PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~UdpSocket ()
 
void connect (const std::string &hostname, int port)
 Connect as an UDP client. More...
 
void connect (int port)
 Connect as an UDP server. More...
 
void close ()
 Close the connection. More...
 
- Public Member Functions inherited from Network::NetSocket
 NetSocket (SOCKET_KIND kind, SOCKET_VERSION version=V4)
 
 NetSocket (SOCKET_KIND kind, PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~NetSocket ()
 
virtual void writeto (const std::string &str, const std::string &host, int port)
 function used to send a msg to a specific host (UDP) More...
 
std::string read ()
 function used by >> operator (read a string on current socket) More...
 
std::string read (int timeout)
 read a string with a timeout More...
 
std::string read (int &port, std::string &host)
 Get a line from socket and store client hostname and port in port and host variable. More...
 
std::string read (int &port, std::string &host, int timeout)
 Get a line from socket and store client hostname and port in port and host variable (with a timeout on listen) More...
 
std::string readn (unsigned int size)
 read a string from socket More...
 
std::string readn (int timeout, unsigned int size)
 read a string with a timeout More...
 
std::string readn (int &port, std::string &host, unsigned int size)
 Get a line from socket and store client hostname and port in port and host variable. More...
 
std::string readn (int &port, std::string &host, int timeout, unsigned int size)
 Get a line from socket and store client hostname and port in port and host variable (with a timeout on listen) More...
 
- Public Member Functions inherited from Network::Socket
 Socket (SOCKET_KIND kind, SOCKET_VERSION version=V4)
 
 Socket (SOCKET_KIND kind, PROTO_KIND pkind, SOCKET_VERSION version=V4)
 
virtual ~Socket ()
 
void write (const std::string &str)
 function used by << operator (write a string on current socket) More...
 
bool connected () const
 return true when socket is connected More...
 
int get_socket ()
 get socket (fd) warning: be very carefull with this method More...
 
void add_delim (const std::string &delim)
 set the delimitor for the text mode More...
 
void del_delim (const std::string &delim)
 delete this delimitor for the socket More...
 
void allow_empty_lines ()
 , if set, empty lines will be returned in text procols (if not, they are skipped) More...
 
void init_tls (GnuTLSKind kind, unsigned size=1024, const std::string &certfile="", const std::string &keyfile="", const std::string &trustfile="", const std::string &crlfile="")
 
Exceptions
TLSSupportErrorwhen TLS is not enabled
More...
 
void enable_tls ()
 Enable TLS on socket. More...
 

Protected Member Functions

std::string _read_line_bin (int socket, int &port, std::string &host, unsigned int pkg_size)
 Get a line from socket and store client hostname and port in port and host variable (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection
GetpeernameErrorwhen getpeername libc function return a negative value.
More...
 
std::string _read_line_bin (int socket, unsigned int size)
 Get a line from socket (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
- Protected Member Functions inherited from Network::NetSocket
struct sockaddr_in _get_addr (int port) const
 internal function (construct a sockaddr) More...
 
struct sockaddr_in _get_addr (const std::string &host, int port) const
 internal function (construct a sockaddr)

Exceptions
HostnameErrorwhen host is incorrect
More...
 
int _bind (int port, const std::string &host)
 Bind a UDP server

Exceptions
SocketErrorwhen socket libc function return a negative value
Exceptionif the selected protocole is incorrect (is you receive this exception, please submit a bug report)
More...
 
int _bind (int port)
 Bind a TCP server

Exceptions
SocketErrorwhen socket libc function return a negative value
SetsockoptErrorwhen setsockopt libc function return a negative value
BindErrorwhen bind libc function return a negative value
Exceptionif the selected protocole is incorrect (is you receive this exception, please submit a bug report)
More...
 
int _accept (int port, int server_socket) const
 Wait for a client

Exceptions
AcceptErrorwhen accept libc function return a negative value.
More...
 
std::string _get_ip (int port, int socket) const
 Get Client Ip. More...
 
void _connect (int socket, int port, const std::string &host) const
 Connect to a hostname

Exceptions
ConnectErrorwhen connect libc function return a negative value.
More...
 
std::string _read_line (int socket)
 Get a line from socket (when used with textual protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
std::string _read_line (int socket, int &port, std::string &host)
 Get a line from socket and store client hostname and port in port and host variable (when used with textual protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection
GetpeernameErrorwhen getpeername libc function return a negative value.
More...
 
void _write_str (int socket, const std::string &str, const std::string &host, int port) const
 Write a string to a socket to a particular host (UDP) (when used with textual protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
void _write_str_bin (int socket, const std::string &str, const std::string &host, int port) const
 Write a string to a socket to a particular host (UDP) (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
- Protected Member Functions inherited from Network::Socket
void _close (int socket) const
 Close a connnection

Exceptions
CloseExceptionwhen close libc function return a negative value.
More...
 
void _listen (int socket) const
 Listen on port

Exceptions
ListenExceptionwhen listen libc function return a negative value.
More...
 
void _write_str (int socket, const std::string &str) const
 Write a string to a socket (when used with textual protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
void _write_str_bin (int socket, const std::string &str) const
 Write a string to a socket (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.
More...
 
void _set_timeout (bool enable, int socket, int timeout)
 set a timeout on a socket More...
 
std::pair< int, int > _find_delim (const std::string &str, int start) const
 
bool _update_buffer (std::pair< int, int > &delim, int &i, std::string &str)
 look delimiter and remove delimiter at begining of buffer if needed More...
 
bool _check_answer (int res, std::string &str)
 return the content of the buffer is there is More...
 

Additional Inherited Members

- Protected Attributes inherited from Network::NetSocket
int _port
 
- Protected Attributes inherited from Network::Socket
SOCKET_KIND _kind
 
SOCKET_VERSION _version
 
unsigned _state_timeout
 
int _socket
 
int _recv_flags
 
struct sockaddr_in _addr
 
PROTO_KIND _proto_kind
 
std::list< std::string > _delim
 
bool _empty_lines
 
std::string _buffer
 
bool _tls
 

Detailed Description

This class represent a udp connection (client and server)

Author
Julien Lemoine <speedblue at="" happycoders="" dot="" org>="">

Definition at line 32 of file udpsocket.hh.

Constructor & Destructor Documentation

Network::UdpSocket::UdpSocket ( SOCKET_VERSION  version = V4)
inline

Definition at line 35 of file udpsocket.hh.

35  :
36  NetSocket(UDP, version)
37  {}
NetSocket(SOCKET_KIND kind, SOCKET_VERSION version=V4)
Definition: netsocket.hh:36
Network::UdpSocket::UdpSocket ( PROTO_KIND  pkind,
SOCKET_VERSION  version = V4 
)
inline

Definition at line 38 of file udpsocket.hh.

38  :
39  NetSocket(UDP, pkind, version)
40  {}
NetSocket(SOCKET_KIND kind, SOCKET_VERSION version=V4)
Definition: netsocket.hh:36
virtual Network::UdpSocket::~UdpSocket ( )
inlinevirtual

Definition at line 42 of file udpsocket.hh.

References close().

43  {
44  close();
45  }
void close()
Close the connection.
Definition: udpsocket.cc:39

Member Function Documentation

std::string Network::UdpSocket::_read_line_bin ( int  socket,
int &  port,
std::string &  host,
unsigned int  pkg_size 
)
protectedvirtual

Get a line from socket and store client hostname and port in port and host variable (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection
GetpeernameErrorwhen getpeername libc function return a negative value.

Implements Network::NetSocket.

Definition at line 101 of file udpsocket.cc.

References Network::Socket::_buffer, Network::Socket::_version, HERE, and Network::V4.

104  {
105  char chr[MAXPKTSIZE];
106  std::string str = "";
107  int res = 1;
108  struct sockaddr_in addr;
109 #ifdef IPV6_ENABLED
110  struct sockaddr_in6 addr6;
111 #endif
112 #ifdef LIBSOCKET_WIN
113  int size;
114 #else
115  socklen_t size;
116 #endif
117  bool end = false;
118 
119 #ifdef IPV6_ENABLED
120  if (V4 == _version)
121 #endif
122  size = sizeof(addr);
123 #ifdef IPV6_ENABLED
124  else
125  size = sizeof(addr6);
126 #endif
127  if (socket < 0)
128  throw NoConnection("No Socket", HERE);
129  if (_buffer.size() >= 2 && !pkg_size)
130  {
131  pkg_size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
132  _buffer = _buffer.substr(2, _buffer.size() - 2);
133  }
134  if (pkg_size && _buffer.size() >= pkg_size)
135  {
136  str = _buffer.substr(0, pkg_size);
137  _buffer = _buffer.substr(pkg_size, _buffer.size() - pkg_size);
138  }
139  else
140  while (!end)
141  {
142 #ifdef LIBSOCKET_WIN
143  int flags = 0;
144 #else
145  int flags = MSG_TRUNC;
146 #endif
147 #ifdef IPV6_ENABLED
148  if (V4 == _version)
149 #endif
150  res = recvfrom(socket, chr, MAXPKTSIZE, flags,
151  (struct sockaddr *) &addr, &size);
152 #ifdef IPV6_ENABLED
153  else
154  res = recvfrom(socket, chr, MAXPKTSIZE, flags,
155  (struct sockaddr *) &addr6, &size);
156 #endif
157  if (res <= 0)
158  throw ConnectionClosed("Connection Closed", HERE);
159  // _buffer += all octets received
160  _buffer += std::string(chr, res).substr(0, res);
161  if (!pkg_size)
162  {
163  // extract size from _buffer and reduce it
164  pkg_size = (unsigned char)_buffer[0] * 256 +
165  (unsigned char)_buffer[1];
166  _buffer = _buffer.substr(2, _buffer.size() - 2);
167  }
168  if (_buffer.size() > pkg_size - str.size())
169  {
170  str += _buffer.substr(0, pkg_size - str.size());
171  _buffer = _buffer.substr(pkg_size - str.size(),
172  _buffer.size() - pkg_size - str.size());
173  }
174  else
175  {
176  str += _buffer;
177  _buffer = "";
178  }
179  if (str.size() >= pkg_size)
180  end = true;
181  }
182 #ifdef IPV6_ENABLED
183  if (V4 == _version)
184  {
185 #endif
186  host = std::string(inet_ntoa(addr.sin_addr));
187  port = ntohs(addr.sin_port);
188 #ifdef IPV6_ENABLED
189  }
190  else
191  {
192  char buf[INET6_ADDRSTRLEN];
193  if (inet_ntop(AF_INET6, &addr6.sin6_addr, buf, INET6_ADDRSTRLEN) == 0)
194  throw InetntopError("Not a valid address", HERE);
195  host = std::string(buf);
196  port = ntohs(addr6.sin6_port);
197  }
198 #endif
199  return str;
200  }
std::string _buffer
Definition: socket.hh:202
SOCKET_VERSION _version
Definition: socket.hh:191
#define HERE
std::string Network::UdpSocket::_read_line_bin ( int  socket,
unsigned int  size 
)
protectedvirtual

Get a line from socket (when used with binary protocol)

Exceptions
NoConnectionwhen there is no open socket
ConnectionClosedwhen there is no more connection.

Implements Network::NetSocket.

Definition at line 46 of file udpsocket.cc.

References Network::Socket::_buffer, and HERE.

47  {
48  char chr[MAXPKTSIZE];
49  std::string str = "";
50  int res = 1;
51  bool end = false;
52 
53  if (socket < 0)
54  throw NoConnection("No Socket", HERE);
55  if (_buffer.size() >= 2 && !size)
56  {
57  size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
58  _buffer = _buffer.substr(2, _buffer.size() - 2);
59  }
60  if (size && _buffer.size() >= size)
61  {
62  str = _buffer.substr(0, size);
63  _buffer = _buffer.substr(size, _buffer.size() - size);
64  }
65  else
66  while (!end)
67  {
68  memset(chr, 0, MAXPKTSIZE);
69 #ifdef LIBSOCKET_WIN
70  res = recv(socket, chr, MAXPKTSIZE, 0);
71 #else
72  res = recv(socket, chr, MAXPKTSIZE, MSG_TRUNC);
73 #endif
74  if (res <= 0)
75  throw ConnectionClosed("Connection Closed", HERE);
76  // _buffer += all octets received
77  _buffer += std::string(chr, res);
78  if (!size)
79  {
80  // extract size from _buffer and reduce it
81  size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
82  _buffer = _buffer.substr(2, _buffer.size() - 2);
83  }
84  if (_buffer.size() > size - str.size())
85  {
86  str += _buffer.substr(0, size - str.size());
87  _buffer = _buffer.substr(size - str.size(),
88  _buffer.size() - size - str.size());
89  }
90  else
91  {
92  str += _buffer;
93  _buffer = "";
94  }
95  if (str.size() >= size)
96  end = true;
97  }
98  return str;
99  }
std::string _buffer
Definition: socket.hh:202
#define HERE
void Network::UdpSocket::close ( )

Close the connection.

Definition at line 39 of file udpsocket.cc.

References Network::Socket::_close(), and Network::Socket::_socket.

Referenced by ~UdpSocket().

40  {
41  if (_socket > 0)
42  _close(_socket);
43  _socket = 0;
44  }
void _close(int socket) const
Close a connnection when close libc function return a negative value.
Definition: socket.cc:167
void Network::UdpSocket::connect ( const std::string &  hostname,
int  port 
)

Connect as an UDP client.

Here is an example of an UDP client using libsocket:

#include <stdlib.h>
#include <iostream>
#include <string>
#include "socket/udpsocket.hh"
int main(int argc, char **argv)
{
  Network::UdpSocket            client;
  //Network::UdpSocket            client(Network::V6);
  // For IPV6 mode
  std::string                   str;
  if (argc < 3)
    {
      std::cout << "Use: " << argv[0] << " port hostname" << std::endl;
      exit(0);
    }
  try
    {
      client.connect(std::string(argv[2]), strtol(argv[1], NULL, 10));
      while (str != "quit")
        {
          std::cin >> str;
          client << str;
        }
      client.close();
      exit(0);
    }
  catch (Network::Exception e)
    {
      std::cerr << e;
      exit(1);
    }
}

Definition at line 27 of file udpsocket.cc.

References Network::NetSocket::_bind(), Network::NetSocket::_port, and Network::Socket::_socket.

28  {
29  _port = port;
30  _socket = _bind(port, hostname);
31  }
int _bind(int port, const std::string &host)
Bind a UDP server when socket libc function return a negative value if the selected protocole is inco...
Definition: netsocket.cc:86
void Network::UdpSocket::connect ( int  port)

Connect as an UDP server.

Here is an example of an UDP server using libsocket :

#include <stdlib.h>
#include <iostream>
#include <string>
#include "socket/udpsocket.hh"
#include "exception/exception.hh"
int main(int argc, char **argv)
{
  Network::UdpSocket            server;
  std::string                   str, host;
  if (argc < 2)
    {
      std::cout << "Use: " << argv[0] << " port" << std::endl;
      exit(0);
    }
  try
    {
      server.connect(strtol(argv[1], NULL, 10));
      while (str != "quit")
        {
                 //read with a timeout of 30 seconds and get client host and port
                 str = server.read(port, host, 30);
                 std::cout << "Received [" << str << "] from : " << host
                           << ":" << port << "]" << std::endl;
               }
      server.close();
      exit (0);
    }
  catch (Network::Timeout e)
    {
      std::cerr << e;
      std::cerr << "No connection during last 30s, closing connection"
                << std::endl;
      exit (1);
    }
  catch (Network::Exception e)
    {
      std::cerr << e;
      exit(1);
    }
}

Definition at line 33 of file udpsocket.cc.

References Network::NetSocket::_bind(), Network::NetSocket::_port, and Network::Socket::_socket.

34  {
35  _socket = _bind(port);
36  _port = port;
37  }
int _bind(int port, const std::string &host)
Bind a UDP server when socket libc function return a negative value if the selected protocole is inco...
Definition: netsocket.cc:86

The documentation for this class was generated from the following files: