-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.cpp
More file actions
72 lines (62 loc) · 1.44 KB
/
server.cpp
File metadata and controls
72 lines (62 loc) · 1.44 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
#include "server.hpp"
Server::Server(std::string ip, std::string port)
{
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int r = getaddrinfo(ip.c_str(), port.c_str(), &hints, &server);
if (r != 0)
{
std::cout << "faild" << std::endl;
}
sockfd = socket(server->ai_family,server->ai_socktype, server->ai_protocol);
if (sockfd == -1)
{
std::cout << "error in creating socket" << std::endl;
}
pollfd pfd;
pfd.fd = this->sockfd;
pfd.events = POLLIN;
pfd.revents = 0;
this->fds.push_back(pfd);
}
Server::~Server()
{
freeaddrinfo(this->server);
close(this->sockfd);
std::cout << "server closed" << std::endl;
}
void Server::bind_socket()
{
int r = bind(sockfd, server->ai_addr, server->ai_addrlen);
if ( r == -1)
{
std::cout << "error in bind function" << std::endl;
}
}
void Server::setsockopt()
{
int opt = 1;
int r = ::setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (r == -1)
{
std::cout << "error in setsockopt function" << std::endl;
}
}
void Server::listen_socket()
{
int r = listen(sockfd, 1000);
if(r == -1)
{
std::cout << "error in listen function" << std::endl;
}
}
int Server::get_sockfd()
{
return this->sockfd;
}
std::vector<pollfd> Server::get_fds()
{
return this->fds;
}