Zappy Server
C++ game server: world, rules, scheduler, network
Loading...
Searching...
No Matches
Listener.cpp
Go to the documentation of this file.
1#include "Listener.hpp"
2
3#include <netinet/in.h>
4#include <sys/socket.h>
5#include <unistd.h>
6
7#include <cerrno>
8#include <cstring>
9#include <string>
10
12{
13 if (port < 1 || port > 65535) throw ListenerException("invalid port: " + std::to_string(port));
14
15 _fd = socket(AF_INET, SOCK_STREAM, 0);
16 if (_fd < 0) throw ListenerException("socket() failed: " + std::string(strerror(errno)));
17
18 int opt = 1;
19 setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
20
21 sockaddr_in addr{};
22 addr.sin_family = AF_INET;
23 addr.sin_addr.s_addr = INADDR_ANY;
24 addr.sin_port = htons(static_cast<uint16_t>(port));
25
26 if (bind(_fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
27 close(_fd);
28 throw ListenerException("bind() failed on port " + std::to_string(port) + ": " +
29 strerror(errno));
30 }
31
32 if (listen(_fd, SOMAXCONN) < 0) {
33 close(_fd);
34 throw ListenerException("listen() failed: " + std::string(strerror(errno)));
35 }
36}
37
39{
40 if (_fd >= 0) close(_fd);
41}
42
43int Listener::fd() const { return _fd; }
44
46{
47 sockaddr_in clientAddr{};
48 socklen_t len = sizeof(clientAddr);
49 return ::accept(_fd, reinterpret_cast<sockaddr*>(&clientAddr), &len);
50}
int fd() const
The listening socket fd (to register in poll()).
Definition Listener.cpp:43
int accept() const
Accept one pending client; returns its new socket fd.
Definition Listener.cpp:45
Listener(int port)
Bind and listen on port.
Definition Listener.cpp:11