-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.cpp
More file actions
80 lines (71 loc) · 2.13 KB
/
utils.cpp
File metadata and controls
80 lines (71 loc) · 2.13 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
#include"utils.h"
#include<iostream>
#include<time.h>
#include<ctime>
#include<iomanip>
void InitSocketAddr(std::string& ip, uint16_t port, sockaddr_in* addr){
memset((char*)addr, 0, sizeof(sockaddr_in));
addr->sin_family = AF_INET;
addr->sin_port = htons(port);
#ifndef LINUX
addr->sin_addr.S_un.S_addr = inet_addr(ip.c_str());
#else
addr->sin_addr.s_addr = inet_addr(ip.c_str());
#endif
}
std::string GetLocalTime(){
std::time_t now = time(NULL);
struct tm* t = localtime(&now);
std::ostringstream os;
os << std::setw(4) << (t->tm_year + 1900);
os << '-' << std::setw(2) << std::setfill('0') << t->tm_mon + 1 << '-' << std::setw(2) << std::setfill('0') << t->tm_mday
<< " " << std::setw(2) << std::setfill('0') << t->tm_hour
<< ':' << std::setw(2) << std::setfill('0') << t->tm_min
<< ':' << std::setw(2) << std::setfill('0') << t->tm_sec << " ";
return os.str();
}
int SetNonBlock(int fd){
int flags;
flags = fcntl(fd, F_GETFL);
if (flags < 0) return flags;
flags |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0){
perror("fcntl set nonblock error : ");
return -1;
}
return 0;
}
int SetReuseAddr(int fd){
int on = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < -1){
perror("setsocketopt so_reuseaddr error : ");
return -1;
}
return 0;
}
int SetRecvSendBufSize(int fd, int size){
if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size,sizeof(size)) < 0){
perror("setsocketopt so_recbuf error : ");
return -1;
}
if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size,sizeof(size)) < 0){
perror("setsocketopt so_sndbuf error : ");
return -1;
}
return 0;
}
int SetKeepLive(int fd, int idle, int interval, int count){
if ( setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void *)&idle, sizeof(idle)) < 0 ){
perror("setsocketopt tcp_keepidle error : ");
return -1;
}
if ( setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void *)&interval, sizeof(idle)) < 0 ){
perror("setsocketopt tcp_keepintvl error : ");
return -1;
}
if ( setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void *)&count, sizeof(count)) < 0 ){
perror("setsocketopt tcp_keepcnt error : ");
return -1;
}
return 0;
}