#include #include #include #include #include #include #include #include using namespace std; #define _CONNECT 0 #define _BIND 1 #define _BUFF_SIZE 512 //bytes //ERROR CODES #define _ERR 1 #define _ERR_ACC 3 #define _ERR_SOCK 4 #define _ERR_CONNECT 5 #define _ERR_BIND 6 #define _ERR_RECV 7 #define _ERR_SND 8 class cSocket { public: cSocket(char *host, int port, unsigned int mode); int init(); //connects or binds the socket int Send(int socket, char *data); //Send with char* int Send(int socket, string data); //Send with string string recieve(int socket); int waitConn(int *socketNum, sockaddr_in *client); int Close(int socket); int quit(); private: long getIP(char *_host); //resolves hostname int main_sock; //main Socket struct sockaddr_in server; //sockadddr_in for main_sock char buffer[_BUFF_SIZE]; //Output Buffer //std::vector sockets; //stores sockets unsigned int socketMode; //stores Mode int connected; }; cSocket::cSocket(char *host, int port, unsigned int mode) { main_sock = socket(AF_INET, SOCK_STREAM, 0); socketMode = mode; server.sin_port = htons(port); server.sin_family = AF_INET; if(mode == _CONNECT) server.sin_addr.s_addr = getIP(host); else if (mode == _BIND) server.sin_addr.s_addr = INADDR_ANY; // accept on any incoming address connected = 0; }//cSocket int cSocket::init() { if (main_sock == -1) return _ERR_SOCK; if (socketMode == _CONNECT) { if (connect(main_sock , (struct sockaddr *)&server , sizeof(server)) < 0) return _ERR_CONNECT; } else if (socketMode == _BIND) { if( bind(main_sock,(struct sockaddr *)&server , sizeof(server)) < 0) return _ERR_BIND; listen(main_sock , 3); } else return 3; connected = 1; return 0; }//init int cSocket::waitConn(int *socket, sockaddr_in *client) { int sz = sizeof(struct sockaddr_in); int tmpSocket = accept(main_sock, (struct sockaddr *)client, (socklen_t*)&sz); if (tmpSocket < 0) return _ERR_ACC; *socket = tmpSocket; return 0; }//waitConn int cSocket::Send(int socket, char *data) { if (main_sock == -1 || connected < 1) return _ERR_SOCK; if( send(socket, data , strlen(data) , 0) < 0) return _ERR_SND; return 0; }//Send int cSocket::Send(int socket, string data) { const char *cData = data.c_str(); //Convert to char* return Send(socket, cData); }//Send string cSocket::recieve(int socket) { for (int i = 0; i < _BUFF_SIZE; i++) { buffer[i] = 0; } if( recv(socket, buffer , _BUFF_SIZE , 0) < 0) return ""; string ret (buffer); return ret; }//recieve int cSocket::Close(int socket) { close(socket); return 0; }//close int cSocket::quit() { Close(main_sock); main_sock = -1; connected = 0; return 0; }//quit long cSocket::getIP(char *_host) { char ip[100]; struct hostent *he; struct in_addr **addr_list; int i; if ( (he = gethostbyname( _host ) ) == NULL) return 1; addr_list = (struct in_addr **) he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) strcpy(ip , inet_ntoa(*addr_list[i]) ); return inet_addr(ip); }//getIP