-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketHandler.h
More file actions
50 lines (49 loc) · 1.21 KB
/
SocketHandler.h
File metadata and controls
50 lines (49 loc) · 1.21 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
#ifndef MULTIPLAT_INCLUDE
#define MULTIPLAT_INCLUDE
#ifdef _WIN32
#include <WinSock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>
#endif
#endif
class SocketHandler {
public:
SocketHandler(int port) {
this->port=port;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
perror("Unable to create socket");
return;
}
if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
perror("Unable to bind");
return;
}
if (listen(sock, 1) == SOCKET_ERROR) {
perror("Unable to listen");
return;
}
}
~SocketHandler() { closeSocket(sock); }
SOCKET* getSocket() { return &sock; }
int* getPort() { return &port; }
private:
SOCKET sock;
int port;
void closeSocket(SOCKET s) {
#ifdef _WIN32
closesocket(s);
#else
::close(s);
#endif
}
};