-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockaddr.c
48 lines (37 loc) · 1.15 KB
/
sockaddr.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
// SPDX-License-Identifier: MIT
#include "sockaddr.h"
#include <arpa/inet.h>
#include <string.h>
socklen_t
sockaddr_parse(struct sockaddr_storage *ss, const char *address, uint16_t port) {
explicit_bzero(ss, sizeof *ss);
struct sockaddr_in *sin = (struct sockaddr_in*)ss;
if (inet_pton(AF_INET, address, &sin->sin_addr) > 0) {
ss->ss_family = AF_INET;
sin->sin_port = htons(port);
return sizeof *sin;
}
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ss;
if (inet_pton(AF_INET6, address, &sin6->sin6_addr) > 0) {
ss->ss_family = AF_INET6;
sin6->sin6_port = htons(port);
return sizeof *sin6;
}
return 0;
}
bool
sockaddr_unparse(const struct sockaddr *sa, char *buf, socklen_t len) {
switch(sa->sa_family) {
case AF_INET: {
struct sockaddr_in *sin = (struct sockaddr_in*)sa;
return !!inet_ntop(sin->sin_family, &sin->sin_addr, buf, len);
}
case AF_INET6: {
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
return !!inet_ntop(sin6->sin6_family, &sin6->sin6_addr, buf, len);
}
default:
return false;
}
}
//