Skip to content
connection.cc 1.52 KiB
Newer Older
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#include "slc.hh"
#include "options.hh"
#include "connection.hh"
#include "screen.hh"
#include "error.hh"

Connection::Connection() : socket_(0) {}

void Connection::start() {
  // make connection
  connect_(O.server.c_str(), O.port);

  // send login info

  // send pass info


  return;
}

void Connection::stop() {
  return;
}

void Connection::connect_(const char *addr, int port) {
  struct sockaddr_in daddr;
  struct hostent *h;

  // Check no existing connexion
  assert(socket_ == 0);

  // retrieve remote host info
  h = gethostbyname(addr);
  if (h == 0)
    throw Error(ERR_NET, (string) "gethostbyname(" + addr  + "): " + hstrerror(h_errno));

  // create socket
  socket_ = socket(PF_INET, SOCK_STREAM, 0);
  if (socket_ == -1)
    throw Error(ERR_NET, (string) "socket: " + strerror(errno));

  daddr.sin_family = AF_INET;
  daddr.sin_port = htons(port);
  daddr.sin_addr = *((struct in_addr *) h->h_addr);
  memset(daddr.sin_zero, '\0', sizeof daddr.sin_zero);

  S << "Connecting to "  << h->h_name  << " (" << inet_ntoa(*(struct in_addr*)h->h_addr)
    << ") on port " << port << "...\n";

  // connect
  if (connect(socket_, (struct sockaddr *) &daddr, sizeof daddr) == -1)
    throw Error(ERR_NET, strerror(errno));

  S << "Connected to " << h->h_name << " (" << inet_ntoa(*(struct in_addr*)h->h_addr)
    << ") on port " << port << "...\n";
}

void Connection::disconnect_() {
  if (socket_ == 0)
    return;

  socket_ = 0;
}