tobicore  7.0.0
 All Classes Functions Variables Typedefs Enumerator Friends Groups Pages
TPSocket.hpp
1 /*
2  Copyright (C) 2009-2011 EPFL (Ecole Polytechnique Fédérale de Lausanne)
3  Michele Tavella <michele.tavella@epfl.ch>
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 3 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, see <http://www.gnu.org/licenses/>.
17 
18  TPSocket.hpp/.cpp is adapted from libtransport
19 */
20 
21 #ifndef TPSOCKET_HPP
22 #define TPSOCKET_HPP
23 
24 #ifdef _WIN32
25 #define UNICODE
26 #define _WIN32_WINNT 0x0501
27 #include <winsock2.h>
28 #include <ws2tcpip.h>
29 #else
30 #include <arpa/inet.h>
31 #include <netdb.h>
32 #endif
33 #include <string>
34 
41 class TPHost {
42  public:
44  TPHost(void);
45 
46  public:
48  const static size_t AddressSize = INET_ADDRSTRLEN + 1;
52  short unsigned int port;
53 };
54 
61 class TPSocket {
62  public:
67  TPSocket(int type = TPSocket::TCP, size_t bsize = 4096);
68 
71  virtual ~TPSocket(void);
72 
77  bool Open(bool asserver);
78 
81  bool Close(void);
82 
86  bool Async(bool block);
87 
96  bool Bind(const std::string &ip, const std::string& port);
97 
101  bool Listen(void);
102 
106  int Accept(TPSocket* endpoint);
107 
116  bool Connect(const std::string& ip, const std::string& port);
117 
122  ssize_t Send(const std::string& message);
123 
128  ssize_t Recv(std::string* message);
129 
133  bool IsConnected(void);
134 
135 #ifdef _WIN32
136  static bool InitializeWSA(void);
137 #endif
138 
139  protected:
141  void Init(void);
143  void Free(void);
144 
146  bool GetLocal(void);
148  bool GetRemote(void);
150  void GetMaxBSize(void);
151 
152  public:
155 
158 
159  enum {
161  TCP = 0,
163  UDP = 1
164  };
165 
166  protected:
168  int _fd;
170  struct sockaddr_in _address;
172  struct sockaddr_storage _endpoint;
174  void* _buffer;
176  size_t _bsize;
178  unsigned int _mc;
180  struct addrinfo _results;
182  struct addrinfo* _info;
184  size_t _bsizemax;
185  private:
187  int _type;
188 #ifdef _WIN32
189  static bool _wsaInitialized;
190 #endif
191 };
192 
193 #endif