Moving Java drivers; Creating iotruntime socket connections for C++; First version...
[iot2.git] / iotjava / iotruntime / cpp / socket / Socket.hpp
1 /*
2  *   C++ sockets on Unix and Windows
3  *   Copyright (C) 2002
4  *
5  *   This program is free software; you can redistribute it and/or modify
6  *   it under the terms of the GNU General Public License as published by
7  *   the Free Software Foundation; either version 2 of the License, or
8  *   (at your option) any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 // http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/
21 #ifndef __SOCKET_
22 #define __SOCKET_
23
24 #include <string>            // For string
25 #include <exception>         // For exception class
26
27 using namespace std;
28
29 /**
30  *   Signals a problem with the execution of a socket call.
31  */
32 class SocketException : public exception {
33 public:
34   /**
35    *   Construct a SocketException with a explanatory message.
36    *   @param message explanatory message
37    *   @param incSysMsg true if system message (from strerror(errno))
38    *   should be postfixed to the user provided message
39    */
40   SocketException(const string &message, bool inclSysMsg = false) throw();
41
42   /**
43    *   Provided just to guarantee that no exceptions are thrown.
44    */
45   ~SocketException() throw();
46
47   /**
48    *   Get the exception message
49    *   @return exception message
50    */
51   const char *what() const throw();
52
53 private:
54   string userMessage;  // Exception message
55 };
56
57 /**
58  *   Base class representing basic communication endpoint
59  */
60 class Socket {
61 public:
62   /**
63    *   Close and deallocate this socket
64    */
65   ~Socket();
66
67   /**
68    *   Get the local address
69    *   @return local address of socket
70    *   @exception SocketException thrown if fetch fails
71    */
72   string getLocalAddress() throw(SocketException);
73
74   /**
75    *   Get the local port
76    *   @return local port of socket
77    *   @exception SocketException thrown if fetch fails
78    */
79   unsigned short getLocalPort() throw(SocketException);
80
81   /**
82    *   Set the local port to the specified port and the local address
83    *   to any interface
84    *   @param localPort local port
85    *   @exception SocketException thrown if setting local port fails
86    */
87   void setLocalPort(unsigned short localPort) throw(SocketException);
88
89   /**
90    *   Set the local port to the specified port and the local address
91    *   to the specified address.  If you omit the port, a random port 
92    *   will be selected.
93    *   @param localAddress local address
94    *   @param localPort local port
95    *   @exception SocketException thrown if setting local port or address fails
96    */
97   void setLocalAddressAndPort(const string &localAddress, 
98     unsigned short localPort = 0) throw(SocketException);
99
100   /**
101    *   If WinSock, unload the WinSock DLLs; otherwise do nothing.  We ignore
102    *   this in our sample client code but include it in the library for
103    *   completeness.  If you are running on Windows and you are concerned
104    *   about DLL resource consumption, call this after you are done with all
105    *   Socket instances.  If you execute this on Windows while some instance of
106    *   Socket exists, you are toast.  For portability of client code, this is 
107    *   an empty function on non-Windows platforms so you can always include it.
108    *   @param buffer buffer to receive the data
109    *   @param bufferLen maximum number of bytes to read into buffer
110    *   @return number of bytes read, 0 for EOF, and -1 for error
111    *   @exception SocketException thrown WinSock clean up fails
112    */
113   static void cleanUp() throw(SocketException);
114
115   /**
116    *   Resolve the specified service for the specified protocol to the
117    *   corresponding port number in host byte order
118    *   @param service service to resolve (e.g., "http")
119    *   @param protocol protocol of service to resolve.  Default is "tcp".
120    */
121   static unsigned short resolveService(const string &service,
122                                        const string &protocol = "tcp");
123
124 private:
125   // Prevent the user from trying to use value semantics on this object
126   Socket(const Socket &sock);
127   void operator=(const Socket &sock);
128
129 protected:
130   int sockDesc;              // Socket descriptor
131   Socket(int type, int protocol) throw(SocketException);
132   Socket(int sockDesc);
133 };
134
135 /**
136  *   Socket which is able to connect, send, and receive
137  */
138 class CommunicatingSocket : public Socket {
139 public:
140   /**
141    *   Establish a socket connection with the given foreign
142    *   address and port
143    *   @param foreignAddress foreign address (IP address or name)
144    *   @param foreignPort foreign port
145    *   @exception SocketException thrown if unable to establish connection
146    */
147   void connect(const string &foreignAddress, unsigned short foreignPort)
148     throw(SocketException);
149
150   /**
151    *   Write the given buffer to this socket.  Call connect() before
152    *   calling send()
153    *   @param buffer buffer to be written
154    *   @param bufferLen number of bytes from buffer to be written
155    *   @exception SocketException thrown if unable to send data
156    */
157   void send(const void *buffer, int bufferLen) throw(SocketException);
158
159   /**
160    *   Read into the given buffer up to bufferLen bytes data from this
161    *   socket.  Call connect() before calling recv()
162    *   @param buffer buffer to receive the data
163    *   @param bufferLen maximum number of bytes to read into buffer
164    *   @return number of bytes read, 0 for EOF, and -1 for error
165    *   @exception SocketException thrown if unable to receive data
166    */
167   int recv(void *buffer, int bufferLen) throw(SocketException);
168
169   /**
170    *   Get the foreign address.  Call connect() before calling recv()
171    *   @return foreign address
172    *   @exception SocketException thrown if unable to fetch foreign address
173    */
174   string getForeignAddress() throw(SocketException);
175
176   /**
177    *   Get the foreign port.  Call connect() before calling recv()
178    *   @return foreign port
179    *   @exception SocketException thrown if unable to fetch foreign port
180    */
181   unsigned short getForeignPort() throw(SocketException);
182
183 protected:
184   CommunicatingSocket(int type, int protocol) throw(SocketException);
185   CommunicatingSocket(int newConnSD);
186 };
187
188 /**
189  *   TCP socket for communication with other TCP sockets
190  */
191 class TCPSocket : public CommunicatingSocket {
192 public:
193   /**
194    *   Construct a TCP socket with no connection
195    *   @exception SocketException thrown if unable to create TCP socket
196    */
197   TCPSocket() throw(SocketException);
198
199   /**
200    *   Construct a TCP socket with a connection to the given foreign address
201    *   and port
202    *   @param foreignAddress foreign address (IP address or name)
203    *   @param foreignPort foreign port
204    *   @exception SocketException thrown if unable to create TCP socket
205    */
206   TCPSocket(const string &foreignAddress, unsigned short foreignPort) 
207       throw(SocketException);
208
209 private:
210   // Access for TCPServerSocket::accept() connection creation
211   friend class TCPServerSocket;
212   TCPSocket(int newConnSD);
213 };
214
215 /**
216  *   TCP socket class for servers
217  */
218 class TCPServerSocket : public Socket {
219 public:
220   /**
221    *   Construct a TCP socket for use with a server, accepting connections
222    *   on the specified port on any interface
223    *   @param localPort local port of server socket, a value of zero will
224    *                   give a system-assigned unused port
225    *   @param queueLen maximum queue length for outstanding 
226    *                   connection requests (default 5)
227    *   @exception SocketException thrown if unable to create TCP server socket
228    */
229   TCPServerSocket(unsigned short localPort, int queueLen = 5) 
230       throw(SocketException);
231
232   /**
233    *   Construct a TCP socket for use with a server, accepting connections
234    *   on the specified port on the interface specified by the given address
235    *   @param localAddress local interface (address) of server socket
236    *   @param localPort local port of server socket
237    *   @param queueLen maximum queue length for outstanding 
238    *                   connection requests (default 5)
239    *   @exception SocketException thrown if unable to create TCP server socket
240    */
241   TCPServerSocket(const string &localAddress, unsigned short localPort,
242       int queueLen = 5) throw(SocketException);
243
244   /**
245    *   Blocks until a new connection is established on this socket or error
246    *   @return new connection socket
247    *   @exception SocketException thrown if attempt to accept a new connection fails
248    */
249   TCPSocket *accept() throw(SocketException);
250
251 private:
252   void setListen(int queueLen) throw(SocketException);
253 };
254
255 /**
256   *   UDP socket class
257   */
258 class UDPSocket : public CommunicatingSocket {
259 public:
260   /**
261    *   Construct a UDP socket
262    *   @exception SocketException thrown if unable to create UDP socket
263    */
264   UDPSocket() throw(SocketException);
265
266   /**
267    *   Construct a UDP socket with the given local port
268    *   @param localPort local port
269    *   @exception SocketException thrown if unable to create UDP socket
270    */
271   UDPSocket(unsigned short localPort) throw(SocketException);
272
273   /**
274    *   Construct a UDP socket with the given local port and address
275    *   @param localAddress local address
276    *   @param localPort local port
277    *   @exception SocketException thrown if unable to create UDP socket
278    */
279   UDPSocket(const string &localAddress, unsigned short localPort) 
280       throw(SocketException);
281
282   /**
283    *   Unset foreign address and port
284    *   @return true if disassociation is successful
285    *   @exception SocketException thrown if unable to disconnect UDP socket
286    */
287   void disconnect() throw(SocketException);
288
289   /**
290    *   Send the given buffer as a UDP datagram to the
291    *   specified address/port
292    *   @param buffer buffer to be written
293    *   @param bufferLen number of bytes to write
294    *   @param foreignAddress address (IP address or name) to send to
295    *   @param foreignPort port number to send to
296    *   @return true if send is successful
297    *   @exception SocketException thrown if unable to send datagram
298    */
299   void sendTo(const void *buffer, int bufferLen, const string &foreignAddress,
300             unsigned short foreignPort) throw(SocketException);
301
302   /**
303    *   Read read up to bufferLen bytes data from this socket.  The given buffer
304    *   is where the data will be placed
305    *   @param buffer buffer to receive data
306    *   @param bufferLen maximum number of bytes to receive
307    *   @param sourceAddress address of datagram source
308    *   @param sourcePort port of data source
309    *   @return number of bytes received and -1 for error
310    *   @exception SocketException thrown if unable to receive datagram
311    */
312   int recvFrom(void *buffer, int bufferLen, string &sourceAddress, 
313                unsigned short &sourcePort) throw(SocketException);
314
315   /**
316    *   Set the multicast TTL
317    *   @param multicastTTL multicast TTL
318    *   @exception SocketException thrown if unable to set TTL
319    */
320   void setMulticastTTL(unsigned char multicastTTL) throw(SocketException);
321
322   /**
323    *   Join the specified multicast group
324    *   @param multicastGroup multicast group address to join
325    *   @exception SocketException thrown if unable to join group
326    */
327   void joinGroup(const string &multicastGroup) throw(SocketException);
328
329   /**
330    *   Leave the specified multicast group
331    *   @param multicastGroup multicast group address to leave
332    *   @exception SocketException thrown if unable to leave group
333    */
334   void leaveGroup(const string &multicastGroup) throw(SocketException);
335
336 private:
337   void setBroadcast();
338 };
339
340 #endif