regen pidl all: rm epan/dissectors/pidl/*-stamp; pushd epan/dissectors/pidl/ && make...
[wireshark-sm.git] / wsutil / inet_addr.c
blobe0f1df62bc7544669131085f96217e96b4eb7e61
1 /* inet_addr.c
3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
10 #include "config.h"
11 #define WS_LOG_DOMAIN LOG_DOMAIN_WSUTIL
12 #include "inet_addr.h"
14 #include <errno.h>
15 #include <string.h>
17 #ifdef HAVE_ARPA_INET_H
18 #include <arpa/inet.h>
19 #endif
21 #ifdef HAVE_NETINET_IN_H
22 #include <netinet/in.h>
23 #endif
25 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 #include <sys/socket.h> /* needed to define AF_ values on UNIX */
29 #endif
31 #ifdef _WIN32
32 #include <ws2tcpip.h> /* indirectly defines AF_ values on Windows */
33 #define _NTOP_SRC_CAST_ (PVOID)
34 #else
35 #define _NTOP_SRC_CAST_
36 #endif
38 #include "str_util.h"
41 * We assume and require an inet_pton/inet_ntop that supports AF_INET
42 * and AF_INET6.
45 static inline bool
46 inet_pton_internal(int af, const char *src, void *dst, size_t dst_size,
47 const char *af_str)
49 int ret = inet_pton(af, src, dst);
50 if (ret < 0) {
51 int err = errno;
52 ws_log(WS_LOG_DOMAIN, LOG_LEVEL_CRITICAL, "inet_pton: %s (%d): %s", af_str, af, g_strerror(err));
53 memset(dst, 0, dst_size);
54 errno = err;
55 return false;
57 /* ret == 0 invalid src representation, ret == 1 success. */
58 return ret == 1;
61 static inline const char *
62 inet_ntop_internal(int af, const void *src, char *dst, size_t dst_size,
63 const char *af_str)
65 /* Add a cast to ignore 64-to-32 bit narrowing warnings with some
66 * compilers (POSIX uses socklen_t instead of size_t). */
67 const char *ret = inet_ntop(af, _NTOP_SRC_CAST_ src, dst, (unsigned int)dst_size);
68 if (ret == NULL) {
69 int err = errno;
70 char errbuf[16];
71 ws_log(WS_LOG_DOMAIN, LOG_LEVEL_CRITICAL, "inet_ntop: %s (%d): %s", af_str, af, g_strerror(err));
72 /* set result to something that can't be confused with a valid conversion */
73 (void)g_strlcpy(dst, ws_strerrorname_r(err, errbuf, sizeof(errbuf)), dst_size);
74 errno = err;
75 return dst;
77 return dst;
80 const char *
81 ws_inet_ntop4(const void *src, char *dst, size_t dst_size)
83 return inet_ntop_internal(AF_INET, src, dst, dst_size, "AF_INET");
86 bool
87 ws_inet_pton4(const char *src, ws_in4_addr *dst)
89 return inet_pton_internal(AF_INET, src, dst, sizeof(*dst), "AF_INET");
92 const char *
93 ws_inet_ntop6(const void *src, char *dst, size_t dst_size)
95 return inet_ntop_internal(AF_INET6, src, dst, dst_size, "AF_INET6");
98 bool
99 ws_inet_pton6(const char *src, ws_in6_addr *dst)
101 return inet_pton_internal(AF_INET6, src, dst, sizeof(*dst), "AF_INET6");