-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
utils.c
89 lines (76 loc) · 2.03 KB
/
utils.c
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
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include "utils.h"
int make_nonblocking(int fd)
{
int flags = fcntl(fd, F_GETFL);
if (flags != -1) {
if (flags & O_NONBLOCK) {
return 0;
}
flags |= O_NONBLOCK;
return fcntl(fd, F_SETFL, flags);
}
return -1;
}
int safe_accept(int fd, struct sockaddr* addr, socklen_t* addrlen)
{
int res;
do {
res = accept(fd, addr, addrlen);
} while (-1 == res && (EINTR == errno));
return res;
}
ssize_t safe_read(int fd, void* buf, size_t count)
{
ssize_t n;
do {
n = read(fd, buf, count);
} while (-1 == n && (EINTR == errno));
if (-1 == n && (errno == EWOULDBLOCK || errno == EAGAIN)) {
n = -2;
}
return n;
}
ssize_t safe_write(int fd, const void* buf, size_t count)
{
ssize_t n;
do {
n = write(fd, buf, count);
} while (-1 == n && (EINTR == errno));
if (-1 == n && (errno == EWOULDBLOCK || errno == EAGAIN)) {
n = -2;
}
return n;
}
void get_ip_port(const struct sockaddr* addr, char* ipstr, uint16_t* port)
{
assert(addr != NULL);
assert(ipstr != NULL);
assert(port != NULL);
if (addr->sa_family == AF_INET) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
const struct sockaddr_in* s = (const struct sockaddr_in*)addr;
#pragma clang diagnostic pop
*port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, INET6_ADDRSTRLEN);
}
else if (addr->sa_family == AF_INET6) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
const struct sockaddr_in6* s = (const struct sockaddr_in6*)addr;
#pragma clang diagnostic pop
*port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, INET6_ADDRSTRLEN);
}
else {
/* Should not happen */
*ipstr = '\0';
*port = 0;
assert(0);
}
}