/*
* TCP.cpp
* This file is part of VallauriSoft
*
* Copyright (C) 2012 - Comina Francesco
*
* VallauriSoft is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* VallauriSoft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VallauriSoft; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#ifndef _TCP_CPP_
#define _TCP_CPP_
#include "Socket.hpp"
namespace Socket
{
TCP::TCP(void) : CommonSocket(SOCK_STREAM)
{
}
TCP::TCP(const TCP &tcp) : CommonSocket()
{
this->_socket_id = tcp._socket_id;
this->_opened = tcp._opened;
this->_binded = tcp._binded;
}
Ip TCP::ip(void)
{
return this->_address.ip();
}
Port TCP::port(void)
{
return this->_address.port();
}
Address TCP::address(void)
{
return Address(this->_address);
}
void TCP::listen_on_port(Port port, unsigned int listeners = 1)
{
CommonSocket::listen_on_port(port);
if (listen(this->_socket_id, listeners) != 0)
{
stringstream error;
error << "[listen_on_port] with [port=" << port << "] [listeners=" << listeners << "] Cannot bind socket";
throw SocketException(error.str());
}
}
void TCP::connect_to(Address address)
{
if (this->_binded) throw SocketException("[connect_to] Socket already binded to a port, use another socket");
if (!this->_opened) this->open();
if (connect(this->_socket_id, (struct sockaddr*)&address, sizeof(struct sockaddr_in)) < 0)
{
stringstream error;
error << "[connect_to] with [address=" << address << "] Cannot connect to the specified address";
throw SocketException(error.str());
}
this->_binded = true;
}
TCP TCP::accept_client(void)
{
TCP ret;
socklen_t len = sizeof(struct sockaddr_in);
ret.close();
ret._socket_id = accept(this->_socket_id, (struct sockaddr*)&ret._address, &len);
ret._opened = true;
ret._binded = true;
return ret;
}
template