diff options
Diffstat (limited to 'lib/socket.cc')
-rw-r--r-- | lib/socket.cc | 142 |
1 files changed, 139 insertions, 3 deletions
diff --git a/lib/socket.cc b/lib/socket.cc index 6189d23..37e985a 100644 --- a/lib/socket.cc +++ b/lib/socket.cc @@ -24,13 +24,147 @@ * along with MIaV; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ -#include <config.h> - #include "socket.h" + +#include <errno.h> + +// for gethostbyname +#include <netdb.h> + +// for inet_addr +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> + +Socket::Socket(int port, std::string addr) +{ + this->prt = port; + this->addr = addr; + connected = false; +} + +Socket::~Socket() +{ + disconnect(); +} + +int Socket::setPort(int port) +{ + if(connected) { + strerr = "Cannot change port, while socket is connected."; + return 1; + } + + this->prt = port; + return 0; +} + +int Socket::port() +{ + return prt; +} + +int Socket::setAddress(std::string addr) +{ + if(connected) { + strerr = "Cannot change address, while socket is connected."; + return 1; + } + + this->addr = addr; + return 0; +} + +std::string Socket::address() +{ + return addr; +} + +static int _connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen) +{return connect(sockfd, serv_addr, addrlen);} +int Socket::connect() +{ + if(connected) { + strerr = "Could not connect, socket is already connected."; + return 1; + } + + // Do DNS lookup + char *ip; + struct in_addr **addr_list; + struct hostent *he; + he = gethostbyname(addr.c_str()); + if(!he || !he->h_length) { + strerr = hstrerror(h_errno); + return 1; + } + + addr_list = (struct in_addr **)he->h_addr_list; + // for(int i = 0; addr_list[i] != NULL; i++) { + ip = inet_ntoa(*addr_list[0]); + // } + + struct sockaddr_in socketaddr; + memset((char *) &socketaddr, sizeof(socketaddr), 0); + socketaddr.sin_family = AF_INET; + socketaddr.sin_port = htons(prt); + socketaddr.sin_addr.s_addr = inet_addr(ip); + + if(_connect(sock, (struct sockaddr*)&socketaddr, sizeof(socketaddr))) { + strerr = strerror(errno); + return 1; + } + + connected = true; + + return 0; +} + +int Socket::disconnect() +{ + if(!connected) { + strerr = "Could not disconnect, socket is already disconnected."; + return 1; + } + + close(sock); + connected = false; + + return 0; +} + +std::string Socket::error() +{ + return strerr; +} + + + + + + + + + + + + + + + + + + + + + +/* + #include "info.h" #include <errno.h> + Socket::Socket() { connected = false; @@ -73,7 +207,7 @@ Socket Socket::slisten() Socket s; if(err) { - //MIaV::info->error("Socket: No socket present!"); + // MIaV::info->error("Socket: No socket present!"); return s; } if(!connected) { @@ -147,3 +281,5 @@ bool Socket::hasError() { return err != 0; } + +*/ |