-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.cpp
112 lines (93 loc) · 2.22 KB
/
util.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/wait.h>
double time_seconds(void)
{
struct timeval tval;
gettimeofday(&tval,NULL);
return tval.tv_sec + (tval.tv_usec*1.0e-6);
}
/*
open a UDP socket on the given port
*/
int open_socket_in_udp(int port)
{
struct sockaddr_in sock;
int res;
int one=1;
memset(&sock,0,sizeof(sock));
#ifdef HAVE_SOCK_SIN_LEN
sock.sin_len = sizeof(sock);
#endif
sock.sin_port = htons(port);
sock.sin_family = AF_INET;
res = socket(AF_INET, SOCK_DGRAM, 0);
if (res == -1) {
fprintf(stderr, "socket failed\n"); return -1;
return -1;
}
setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
return(-1);
}
return res;
}
/*
open a TCP socket on the given port
*/
int open_socket_in_tcp(int port)
{
struct sockaddr_in sock;
int res;
int one=1;
memset(&sock,0,sizeof(sock));
#ifdef HAVE_SOCK_SIN_LEN
sock.sin_len = sizeof(sock);
#endif
sock.sin_port = htons(port);
sock.sin_family = AF_INET;
res = socket(AF_INET, SOCK_STREAM, 0);
if (res == -1) {
fprintf(stderr, "socket failed\n"); return -1;
return -1;
}
setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
return(-1);
}
if (listen(res, 1) != 0) {
return(-1);
}
setsockopt(res, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
return res;
}
/*
convert address to string, uses a static return buffer
*/
const char *addr_to_str(struct sockaddr_in &addr)
{
static char str[INET_ADDRSTRLEN+1];
inet_ntop(AF_INET, &addr.sin_addr, str, INET_ADDRSTRLEN);
return str;
}
/*
return time as a string, using a static buffer
*/
const char *time_string(void)
{
time_t t = time(nullptr);
struct tm *tm = localtime(&t);
static char str[100] {};
strftime(str, sizeof(str)-1, "%F %T", tm);
return str;
}