#include "tcp_server.h"

net_tools::tcp_server::tcp_server(const string & the_ip, 
                                  const int the_port)
:_ip_address(the_ip), _port(the_port)
{
   int rc = 0;

   _err = false;

   _fd = socket(AF_INET, SOCK_STREAM, 0);

   if(_fd == INVALID_SOCKET)
      _err = true;

   memset((char*)(&_svr), 0, sizeof(_svr));
   memset((char*)(&_cli), 0, sizeof(_cli));

   _svr.sin_family = AF_INET;
   _svr.sin_port = htons(_port);
   _svr.sin_addr.s_addr = inet_addr(_ip_address.c_str());
   
   if(!_err) if(bind(_fd, (const sockaddr *)(&_svr), sizeof(_svr)) == SOCKET_ERROR) _err = true;

   if(!_err) if(listen(_fd, SOMAXCONN) == SOCKET_ERROR) _err = true;
}

net_tools::tcp_server::~tcp_server()
{
   if(!_err) {
      closesocket(_fd);
   }
}

SOCKET
net_tools::tcp_server::accept()
{
   SOCKET fd = INVALID_SOCKET;
   int client;
   if(!_err) {
      client = sizeof(_cli);
      fd = ::accept(_fd, (sockaddr*)(&_cli), &client);
   }
   return fd;
}

void
net_tools::tcp_server::close()
{
   ::closesocket(_fd);
}
