Initial files
[oweals/minetest.git] / src / socket.h
1 #ifndef SOCKET_HEADER
2 #define SOCKET_HEADER
3
4 #ifdef _WIN32
5         #define WIN32_LEAN_AND_MEAN
6         #include <windows.h>
7         #include <winsock2.h>
8         #include <ws2tcpip.h>
9         #pragma comment(lib, "wsock32.lib")
10 typedef SOCKET socket_t;
11 typedef int socklen_t;
12 #else
13         #include <sys/socket.h>
14         #include <netinet/in.h>
15         #include <fcntl.h>
16         #include <netdb.h>
17         #include <unistd.h>
18 typedef int socket_t;
19 #endif
20
21 #include <ostream>
22 #include "exceptions.h"
23 #include "constants.h"
24
25 class SocketException : public BaseException
26 {
27 public:
28         SocketException(const char *s):
29                 BaseException(s)
30         {
31         }
32 };
33
34 class ResolveError : public BaseException
35 {
36 public:
37         ResolveError(const char *s):
38                 BaseException(s)
39         {
40         }
41 };
42
43 class SendFailedException : public BaseException
44 {
45 public:
46         SendFailedException(const char *s):
47                 BaseException(s)
48         {
49         }
50 };
51
52 void sockets_init();
53 void sockets_cleanup();
54
55 class Address
56 {
57 public:
58         Address();
59         Address(unsigned int address, unsigned short port);
60         Address(unsigned int a, unsigned int b,
61                         unsigned int c, unsigned int d,
62                         unsigned short port);
63         bool operator==(Address &address);
64         bool operator!=(Address &address);
65         void Resolve(const char *name);
66         unsigned int getAddress() const;
67         unsigned short getPort() const;
68         void setAddress(unsigned int address);
69         void setPort(unsigned short port);
70         void print(std::ostream *s) const;
71         void print() const;
72 private:
73         unsigned int m_address;
74         unsigned short m_port;
75 };
76
77 class UDPSocket
78 {
79 public:
80         UDPSocket();
81         ~UDPSocket();
82         void Bind(unsigned short port);
83         //void Close();
84         //bool IsOpen();
85         void Send(const Address & destination, const void * data, int size);
86         // Returns -1 if there is no data
87         int Receive(Address & sender, void * data, int size);
88         int GetHandle(); // For debugging purposes only
89         void setTimeoutMs(int timeout_ms);
90         // Returns true if there is data, false if timeout occurred
91         bool WaitData(int timeout_ms);
92 private:
93         int m_handle;
94         int m_timeout_ms;
95 };
96
97 #endif
98