00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #ifndef SOCKET_H
00023 #define SOCKET_H
00024
00025 #include <string>
00026 #include <exception>
00027
00028 #include <errno.h>
00029 #include <netdb.h>
00030 #include <sys/types.h>
00031 #include <sys/socket.h>
00032 #include <netinet/in.h>
00033 #include <arpa/inet.h>
00034 #include <unistd.h>
00035 #include <stdlib.h>
00036 #include <stdio.h>
00037 #include <fcntl.h>
00038
00039 using std::string;
00040 using std::exception;
00041
00042 unsigned int StringtoIP(const string& ip);
00043
00044 string IPtoString(unsigned int ip);
00045
00046 class Buffer;
00047
00048 class TCPSocket {
00049 public:
00050 enum State {
00051 NOT_CONNECTED,
00052 NONBLOCKING_CONNECT,
00053 CONNECTED
00054 };
00055
00056 private:
00057 static const unsigned int max_receive_size = 4096;
00058
00059 unsigned long gethostname(const char *hostname);
00060
00061 int socketDescriptor;
00062 struct sockaddr_in remoteAddr, localAddr;
00063 bool blocking;
00064 State m_state;
00065
00066 void fcntlSetup();
00067
00068 public:
00069 TCPSocket();
00070 ~TCPSocket();
00071
00072
00073 TCPSocket( int fd, struct sockaddr_in addr );
00074
00075 void Connect();
00076 void FinishNonBlockingConnect();
00077 void Disconnect();
00078
00079 int getSocketHandle();
00080
00081 void Send(Buffer& b);
00082
00083 bool Recv(Buffer& b);
00084
00085 bool connected();
00086
00087 void setRemoteHost(const char *host);
00088 void setRemotePort(unsigned short port);
00089 void setRemoteIP(unsigned int ip);
00090
00091 void setBlocking(bool b);
00092 bool isBlocking() const;
00093
00094 State getState() const;
00095
00096 unsigned int getRemoteIP() const;
00097 unsigned short getRemotePort() const;
00098
00099 unsigned int getLocalIP() const;
00100 unsigned short getLocalPort() const;
00101
00102 };
00103
00104 class TCPServer {
00105 private:
00106 int socketDescriptor;
00107 struct sockaddr_in localAddr;
00108
00109 public:
00110 TCPServer();
00111 ~TCPServer();
00112
00113 int getSocketHandle();
00114
00115 void StartServer();
00116 void Disconnect();
00117
00118 bool isStarted() const;
00119
00120
00121 TCPSocket* Accept();
00122
00123 unsigned short getPort() const;
00124 unsigned int getIP() const;
00125
00126 };
00127
00128 class SocketException : exception {
00129 private:
00130 string m_errortext;
00131
00132 public:
00133 SocketException(const string& text);
00134 ~SocketException() throw() { }
00135
00136 const char* what() const throw();
00137 };
00138
00139 #endif