OLD | NEW |
---|---|
(Empty) | |
1 #include <arpa/inet.h> | |
Sam Clegg
2013/08/01 20:50:53
Missing copyright.
torinmr
2013/08/01 22:04:00
Done.
| |
2 #include <errno.h> | |
3 #include <stdio.h> | |
4 #include <string.h> | |
5 #include <sys/socket.h> | |
6 #include <sys/types.h> | |
7 | |
8 #include <iostream> | |
9 #include <sstream> | |
10 #include <string> | |
11 | |
12 static inline uint8_t get_byte(const void *addr, int byte) { | |
Sam Clegg
2013/08/01 20:50:53
We use the "char* " rather than "char *" style.
torinmr
2013/08/01 22:04:00
Done.
| |
13 const char *buf = static_cast<const char*>(addr); | |
14 return static_cast<uint8_t>(buf[byte]); | |
15 } | |
16 | |
17 char *inet_ntoa(struct in_addr in) { | |
Sam Clegg
2013/08/01 20:50:53
Are these functions missing under glibc? If not m
| |
18 static char addr[INET_ADDRSTRLEN]; | |
19 snprintf(addr, INET_ADDRSTRLEN, "%u.%u.%u.%u", | |
20 get_byte(&in, 0), get_byte(&in, 1), | |
21 get_byte(&in, 2), get_byte(&in, 3)); | |
22 return addr; | |
23 } | |
24 | |
25 const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { | |
26 if (AF_INET == af) { | |
27 if (size < INET_ADDRSTRLEN) { | |
28 errno = ENOSPC; | |
29 return NULL; | |
30 } | |
31 struct in_addr in; | |
32 memcpy(&in, src, sizeof(in)); | |
33 char *result = inet_ntoa(in); | |
34 memcpy(dst, result, strlen(result) + 1); | |
35 return dst; | |
36 } | |
37 | |
38 if (AF_INET6 == af) { | |
39 if (size < INET6_ADDRSTRLEN) { | |
40 errno = ENOSPC; | |
41 return NULL; | |
42 } | |
43 const uint8_t *tuples = static_cast<const uint8_t*>(src); | |
44 std::stringstream output; | |
45 for (int i = 0; i < 8; i++) { | |
46 uint16_t tuple = (tuples[2*i] << 8) + tuples[2*i+1]; | |
47 output << std::hex << tuple; | |
48 if (i < 7) { | |
49 output << ":"; | |
50 } | |
51 } | |
52 memcpy(dst, output.str().c_str(), output.str().size() + 1); | |
53 return dst; | |
54 } | |
55 | |
56 errno = EAFNOSUPPORT; | |
57 return NULL; | |
58 } | |
OLD | NEW |