This repository was archived by the owner on Jan 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtility.cpp
88 lines (73 loc) · 2.07 KB
/
Utility.cpp
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
#include "Utility.hpp"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <csignal>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <ctime>
void Utility::info(const char *fmt, ...) {
va_list fmt_args;
fprintf(stderr, "ERROR: ");
va_start(fmt_args, fmt);
vfprintf(stderr, fmt, fmt_args);
va_end(fmt_args);
fprintf(stderr, " (%d; %s)\n", errno, strerror(errno));
}
unsigned Utility::getPort(const char *cPort) {
std::string sPort(cPort);
unsigned long port;
try {
port = std::stoul(sPort);
} catch (...) {
return INVALID_PORT;
}
return (port < MIN_PORT || port > MAX_PORT) ? INVALID_PORT : port;
}
void Utility::_exit(ExitCode code) { exit(static_cast<int>(code)); }
void Utility::setAddrinfo(addrinfo *addr, bool passive) {
memset(addr, 0, sizeof(addrinfo));
addr->ai_family = AF_INET; // IPv4
addr->ai_socktype = SOCK_STREAM;
addr->ai_protocol = IPPROTO_TCP;
addr->ai_flags |= AI_PASSIVE & passive;
}
bool Utility::_getaddrinfo(const char *node, const char *service, addrinfo *hints,
addrinfo **res, bool passive) {
setAddrinfo(hints, passive);
int err = getaddrinfo(node, service, hints, res);
if (err == EAI_SYSTEM || err != 0) {
Utility::info("getaddrinfo: %s", gai_strerror(err));
return false;
}
return true;
}
bool Utility::equalExceptWhitespaceOnEnd(const std::string &msg, const std::string &pat) {
boost::smatch result;
const boost::regex pattern(pat + R"(\s*)");
try {
return boost::regex_match(msg, result, pattern);
}
catch (...) {
return false;
}
}
bool Utility::startsWith(const std::string &s, const std::string &pref) {
return s.substr(0, pref.size()) == pref;
}
int Utility::currentMinutes() {
char buf[3];
time_t now = time(nullptr);
tm tstruct;
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H", &tstruct);
buf[2] = '\0';
int result = 60 * std::stoi(buf);
strftime(buf, sizeof(buf), "%M", &tstruct);
buf[2] = '\0';
result += std::stoi(buf);
return result;
}