forked from grfz/Socket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.hpp
More file actions
132 lines (101 loc) · 3.27 KB
/
Socket.hpp
File metadata and controls
132 lines (101 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#ifndef _SOCKET_HPP_
#define _SOCKET_HPP_
#include <iostream>
#include <sstream>
#include <exception>
#include <string>
#include <stdlib.h>
#include <arpa/inet.h>
#define MAX_BUFFER 1024
using namespace std;
namespace Socket
{
typedef int Socket;
typedef string Ip;
typedef unsigned int Port;
typedef string Data;
typedef struct
{
Ip ip;
Port port;
}Address;
typedef struct
{
Address address;
Data data;
}Datagram;
class Exception
{
private:
string _message;
public:
Exception(string error) { this->_message = error; }
virtual const char* what() { return this->_message.c_str(); }
};
class UDP
{
private:
Socket _socket_id;
bool _binded;
public:
UDP(void)
{
this->_socket_id = socket(AF_INET, SOCK_DGRAM, 0);
if (this->_socket_id == -1) throw Exception("[Constructor] Cannot create socket");
this->_binded = false;
}
~UDP(void)
{
}
void close(void)
{
shutdown(this->_socket_id, SHUT_RDWR);
}
void listen_on_port(Port port)
{
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr=htonl(INADDR_ANY);
address.sin_port=htons(port);
if (this->_binded)
{
this->close();
this->_socket_id = socket(AF_INET, SOCK_DGRAM, 0);
}
if (bind(this->_socket_id, (struct sockaddr*)&address, sizeof(struct sockaddr_in)) == -1)
{
stringstream error;
error << "[listen_on_port] with [port=" << port << "] Cannot bind socket";
throw Exception(error.str());
}
this->_binded = true;
}
void send(Ip ip, Port port, Data data)
{
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(port);
inet_aton(ip.c_str(), &address.sin_addr);
if (sendto(this->_socket_id, (void*)data.c_str(), data.length() + 1, 0, (struct sockaddr*)&address, sizeof(struct sockaddr_in)) == -1)
{
stringstream error;
error << "[send] with [ip=" << ip << "] [port=" << port << "] [data=" << data << "] Cannot send";
throw Exception(error.str());
}
}
Datagram receive()
{
int size = sizeof(struct sockaddr_in);
char *buffer = (char*)malloc(sizeof(char) * MAX_BUFFER);
struct sockaddr_in address;
Datagram ret;
if (recvfrom(this->_socket_id, (void*)buffer, MAX_BUFFER, 0, (struct sockaddr*)&address, (socklen_t*)&size) == -1) throw Exception("[receive] Cannot receive");
ret.data = buffer;
ret.address.ip = inet_ntoa(address.sin_addr);
ret.address.port = address.sin_port;
free(buffer);
return ret;
}
};
}
#endif