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 m_socketDescriptor;
00062 bool m_socketDescriptor_valid;
00063 struct sockaddr_in remoteAddr, localAddr;
00064 bool blocking;
00065 State m_state;
00066
00067 void fcntlSetup();
00068
00069 public:
00070 TCPSocket();
00071 ~TCPSocket();
00072
00073
00074 TCPSocket( int fd, struct sockaddr_in addr );
00075
00076 void Connect();
00077 void FinishNonBlockingConnect();
00078 void Disconnect();
00079
00080 int getSocketHandle();
00081
00082 void Send(Buffer& b);
00083
00084 bool Recv(Buffer& b);
00085
00086 bool connected();
00087
00088 void setRemoteHost(const char *host);
00089 void setRemotePort(unsigned short port);
00090 void setRemoteIP(unsigned int ip);
00091
00092 void setBlocking(bool b);
00093 bool isBlocking() const;
00094
00095 State getState() const;
00096
00097 unsigned int getRemoteIP() const;
00098 unsigned short getRemotePort() const;
00099
00100 unsigned int getLocalIP() const;
00101 unsigned short getLocalPort() const;
00102
00103 };
00104
00105 class TCPServer {
00106 private:
00107 int m_socketDescriptor;
00108 bool m_socketDescriptor_valid;
00109 struct sockaddr_in localAddr;
00110
00111 public:
00112 TCPServer();
00113 ~TCPServer();
00114
00115 int getSocketHandle();
00116
00117 void StartServer();
00118 void StartServer(unsigned short lower, unsigned short upper);
00119 void Disconnect();
00120
00121 bool isStarted() const;
00122
00123
00124 TCPSocket* Accept();
00125
00126 unsigned short getPort() const;
00127 unsigned int getIP() const;
00128
00129 };
00130
00131 class SocketException : exception {
00132 private:
00133 string m_errortext;
00134
00135 public:
00136 SocketException(const string& text);
00137 ~SocketException() throw() { }
00138
00139 const char* what() const throw();
00140 };
00141
00142 #endif