Skip to content
connection.cc 2.1 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) {}
Seblu's avatar
Seblu committed
bool Connection::connected() const {
  return socket_ != 0;
}

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

  // send login info

  // send pass info

}

void Connection::stop() {
Seblu's avatar
Seblu committed
  disconnect_();

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);
Seblu's avatar
Seblu committed
  if (h == 0) {
    S << "Unable to resolve: " << addr  << ": " << hstrerror(h_errno) << ".\n";
    return;
  }

  // create socket
  socket_ = socket(PF_INET, SOCK_STREAM, 0);
Seblu's avatar
Seblu committed
  if (socket_ == -1) {
    S << "Unable to create socket: " << strerror(errno) << ".\n";
    socket_ = 0;
    return;
  }

  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;
}
Seblu's avatar
Seblu committed


void Connection::send(const string &data) {
  send(data.c_str(), data.length());
}

void Connection::send(const char* buf, size_t len) {
  write(socket_, buf, len);
}

void Connection::sendln(const string &data) {
  sendln(data.c_str(), data.length());
}

void Connection::sendln(const char* buf, size_t len) {
  write(socket_, buf, len);
  write(socket_, "\n", 1);
}
Seblu's avatar
Seblu committed

string Connection::recvln() {
  char buf[MAX_LINE_SIZE];

  read(socket_, buf, MAX_LINE_SIZE);
  return buf;
}