1 | /* |
---|
2 | * Replacement for a missing inet_ntop. |
---|
3 | * |
---|
4 | * Provides an implementation of inet_ntop that only supports IPv4 addresses |
---|
5 | * for hosts that are missing it. If you want IPv6 support, you need to have |
---|
6 | * a real inet_ntop function; this function is only provided so that code can |
---|
7 | * call inet_ntop unconditionally without needing to worry about whether the |
---|
8 | * host supports IPv6. |
---|
9 | * |
---|
10 | * Written by Russ Allbery <rra@stanford.edu> |
---|
11 | * This work is hereby placed in the public domain by its author. |
---|
12 | */ |
---|
13 | |
---|
14 | #include <config.h> |
---|
15 | #include <portable/system.h> |
---|
16 | #include <portable/socket.h> |
---|
17 | |
---|
18 | #include <errno.h> |
---|
19 | |
---|
20 | /* This may already be defined by the system headers. */ |
---|
21 | #ifndef INET_ADDRSTRLEN |
---|
22 | # define INET_ADDRSTRLEN 16 |
---|
23 | #endif |
---|
24 | |
---|
25 | /* Systems old enough to not support inet_ntop may not have this either. */ |
---|
26 | #ifndef EAFNOSUPPORT |
---|
27 | # define EAFNOSUPPORT EDOM |
---|
28 | #endif |
---|
29 | |
---|
30 | /* |
---|
31 | * If we're running the test suite, rename inet_ntop to avoid conflicts with |
---|
32 | * the system version. |
---|
33 | */ |
---|
34 | #if TESTING |
---|
35 | # define inet_ntop test_inet_ntop |
---|
36 | const char *test_inet_ntop(int, const void *, char *, socklen_t); |
---|
37 | #endif |
---|
38 | |
---|
39 | const char * |
---|
40 | inet_ntop(int af, const void *src, char *dst, socklen_t cnt) |
---|
41 | { |
---|
42 | const unsigned char *p; |
---|
43 | |
---|
44 | if (af != AF_INET) { |
---|
45 | socket_set_errno(EAFNOSUPPORT); |
---|
46 | return NULL; |
---|
47 | } |
---|
48 | if (cnt < INET_ADDRSTRLEN) { |
---|
49 | errno = ENOSPC; |
---|
50 | return NULL; |
---|
51 | } |
---|
52 | p = src; |
---|
53 | snprintf(dst, cnt, "%u.%u.%u.%u", |
---|
54 | (unsigned int) (p[0] & 0xff), (unsigned int) (p[1] & 0xff), |
---|
55 | (unsigned int) (p[2] & 0xff), (unsigned int) (p[3] & 0xff)); |
---|
56 | return dst; |
---|
57 | } |
---|