Network::UdpSocket Class Reference

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

`#include <udpsocket.hh>`

Inheritance diagram for Network::UdpSocket:

## 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

  TLSSupportError | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when there is no more connection
  GetpeernameError | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when 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

  HostnameError | when host is incorrect

More...

int | _bind (int port, const std::string &host)

Bind a UDP server

Exceptions

  SocketError | when socket libc function return a negative value
  Exception | if 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

  SocketError | when socket libc function return a negative value
  SetsockoptError | when setsockopt libc function return a negative value
  BindError | when bind libc function return a negative value
  Exception | if 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

  AcceptError | when 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

  ConnectError | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when there is no more connection
  GetpeernameError | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when there is no more connection.

More...

Protected Member Functions inherited from Network::Socket
void | _close (int socket) const

Close a connnection

Exceptions

  CloseException | when close libc function return a negative value.

More...

void | _listen (int socket) const

Listen on port

Exceptions

  ListenException | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when 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

  NoConnection | when there is no open socket
  ConnectionClosed | when 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

## 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.

:
NetSocket(UDP, version)
{}

Network::UdpSocket::UdpSocket | ( | PROTO_KIND | pkind,
|  | SOCKET_VERSION | version = `V4`
| ) |  |

inline

Definition at line 38 of file udpsocket.hh.

:
NetSocket(UDP, pkind, version)
{}

virtual Network::UdpSocket::~UdpSocket | ( | ) |  |

inline virtual

Definition at line 42 of file udpsocket.hh.

References close().

{
close();
}

## Member Function Documentation

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

protected virtual

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

Exceptions

  NoConnection | when there is no open socket
  ConnectionClosed | when there is no more connection
  GetpeernameError | when 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.

{
char chr[MAXPKTSIZE];
std::string str = "";
int res = 1;
struct sockaddr_in addr;
#ifdef IPV6_ENABLED
struct sockaddr_in6 addr6;
#endif
#ifdef LIBSOCKET_WIN
int size;
#else
socklen_t size;
#endif
bool end = false;
#ifdef IPV6_ENABLED
if (V4 == _version)
#endif
size = sizeof(addr);
#ifdef IPV6_ENABLED
else
size = sizeof(addr6);
#endif
if (socket < 0)
throw NoConnection("No Socket", HERE);
if (_buffer.size() >= 2 && !pkg_size)
{
pkg_size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
_buffer = _buffer.substr(2, _buffer.size() - 2);
}
if (pkg_size && _buffer.size() >= pkg_size)
{
str = _buffer.substr(0, pkg_size);
_buffer = _buffer.substr(pkg_size, _buffer.size() - pkg_size);
}
else
while (!end)
{
#ifdef LIBSOCKET_WIN
int flags = 0;
#else
int flags = MSG_TRUNC;
#endif
#ifdef IPV6_ENABLED
if (V4 == _version)
#endif
res = recvfrom(socket, chr, MAXPKTSIZE, flags,
(struct sockaddr *) &addr, &size);
#ifdef IPV6_ENABLED
else
res = recvfrom(socket, chr, MAXPKTSIZE, flags,
(struct sockaddr *) &addr6, &size);
#endif
if (res <= 0)
throw ConnectionClosed("Connection Closed", HERE);
// _buffer += all octets received
_buffer += std::string(chr, res).substr(0, res);
if (!pkg_size)
{
// extract size from _buffer and reduce it
pkg_size = (unsigned char)_buffer[0] * 256 +
(unsigned char)_buffer[1];
_buffer = _buffer.substr(2, _buffer.size() - 2);
}
if (_buffer.size() > pkg_size - str.size())
{
str += _buffer.substr(0, pkg_size - str.size());
_buffer = _buffer.substr(pkg_size - str.size(),
_buffer.size() - pkg_size - str.size());
}
else
{
str += _buffer;
_buffer = "";
}
if (str.size() >= pkg_size)
end = true;
}
#ifdef IPV6_ENABLED
if (V4 == _version)
{
#endif
host = std::string(inet_ntoa(addr.sin_addr));
port = ntohs(addr.sin_port);
#ifdef IPV6_ENABLED
}
else
{
char buf[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &addr6.sin6_addr, buf, INET6_ADDRSTRLEN) == 0)
throw InetntopError("Not a valid address", HERE);
host = std::string(buf);
port = ntohs(addr6.sin6_port);
}
#endif
return str;
}

std::string Network::UdpSocket::_read_line_bin | ( | int | socket,
|  | unsigned int | size
| ) |  |

protected virtual

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

Exceptions

  NoConnection | when there is no open socket
  ConnectionClosed | when there is no more connection.

Implements Network::NetSocket.

Definition at line 46 of file udpsocket.cc.

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

{
char chr[MAXPKTSIZE];
std::string str = "";
int res = 1;
bool end = false;
if (socket < 0)
throw NoConnection("No Socket", HERE);
if (_buffer.size() >= 2 && !size)
{
size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
_buffer = _buffer.substr(2, _buffer.size() - 2);
}
if (size && _buffer.size() >= size)
{
str = _buffer.substr(0, size);
_buffer = _buffer.substr(size, _buffer.size() - size);
}
else
while (!end)
{
memset(chr, 0, MAXPKTSIZE);
#ifdef LIBSOCKET_WIN
res = recv(socket, chr, MAXPKTSIZE, 0);
#else
res = recv(socket, chr, MAXPKTSIZE, MSG_TRUNC);
#endif
if (res <= 0)
throw ConnectionClosed("Connection Closed", HERE);
// _buffer += all octets received
_buffer += std::string(chr, res);
if (!size)
{
// extract size from _buffer and reduce it
size = (unsigned char)_buffer[0] * 256 + (unsigned char)_buffer[1];
_buffer = _buffer.substr(2, _buffer.size() - 2);
}
if (_buffer.size() > size - str.size())
{
str += _buffer.substr(0, size - str.size());
_buffer = _buffer.substr(size - str.size(),
_buffer.size() - size - str.size());
}
else
{
str += _buffer;
_buffer = "";
}
if (str.size() >= size)
end = true;
}
return str;
}

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().

{
if (_socket > 0)
_close(_socket);
_socket = 0;
}

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.

{
_port = port;
_socket = _bind(port, hostname);
}

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.

{
_socket = _bind(port);
_port = port;
}

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

- udpsocket.hh
- udpsocket.cc