Newer
Older
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include "screen.hh"
#include "error.hh"
Connection::Connection() : socket_(0) {}
bool Connection::connected() const {
return socket_ != 0;
}
// make connection
connect_(O.server.c_str(), O.port);
// send login info
// send pass info
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) {
S << "Unable to resolve: " << addr << ": " << hstrerror(h_errno) << ".\n";
return;
}
// create socket
socket_ = socket(PF_INET, SOCK_STREAM, 0);
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;
}
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);
}