1 /* addr_and_mask.c
2  * Routines to fetch IPv4 and IPv6 addresses from a tvbuff and then mask
3  * out bits other than those covered by a prefix length
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * SPDX-License-Identifier: GPL-2.0-or-later
10  */
11 
12 #include "config.h"
13 
14 #include <stdlib.h>
15 #include <string.h>
16 
17 #include "tvbuff.h"
18 #include "ipv6.h"
19 #include "addr_and_mask.h"
20 #include <wsutil/ws_assert.h>
21 
22 guint32
ip_get_subnet_mask(const guint32 mask_length)23 ip_get_subnet_mask(const guint32 mask_length)
24 {
25 	static const guint32 masks[33] = {
26 		0x00000000,
27 		0x80000000, 0xc0000000, 0xe0000000, 0xf0000000,
28 		0xf8000000, 0xfc000000, 0xfe000000, 0xff000000,
29 		0xff800000, 0xffc00000, 0xffe00000, 0xfff00000,
30 		0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000,
31 		0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000,
32 		0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00,
33 		0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0,
34 		0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff,
35 	};
36 
37 	ws_assert(mask_length <= 32);
38 
39 	return masks[mask_length];
40 }
41 
42 /*
43  * These routines return the length of the address in bytes on success
44  * and -1 if the prefix length is too long.
45  */
46 
47 int
tvb_get_ipv4_addr_with_prefix_len(tvbuff_t * tvb,int offset,ws_in4_addr * addr,guint32 prefix_len)48 tvb_get_ipv4_addr_with_prefix_len(tvbuff_t *tvb, int offset, ws_in4_addr *addr,
49     guint32 prefix_len)
50 {
51 	guint8 addr_len;
52 
53 	if (prefix_len > 32)
54 		return -1;
55 
56 	addr_len = (prefix_len + 7) / 8;
57 	*addr = 0;
58 	tvb_memcpy(tvb, addr, offset, addr_len);
59 	if (prefix_len % 8)
60 		((guint8*)addr)[addr_len - 1] &= ((0xff00 >> (prefix_len % 8)) & 0xff);
61 	return addr_len;
62 }
63 
64 int
tvb_get_ipv6_addr_with_prefix_len(tvbuff_t * tvb,int offset,ws_in6_addr * addr,guint32 prefix_len)65 tvb_get_ipv6_addr_with_prefix_len(tvbuff_t *tvb, int offset, ws_in6_addr *addr,
66     guint32 prefix_len)
67 {
68 	guint32 addr_len;
69 
70 	if (prefix_len > 128)
71 		return -1;
72 
73 	addr_len = (prefix_len + 7) / 8;
74 	memset(addr->bytes, 0, 16);
75 	tvb_memcpy(tvb, addr->bytes, offset, addr_len);
76 	if (prefix_len % 8) {
77 		addr->bytes[addr_len - 1] &=
78 		    ((0xff00 >> (prefix_len % 8)) & 0xff);
79 	}
80 
81 	return addr_len;
82 }
83 
84 /*
85  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
86  *
87  * Local variables:
88  * c-basic-offset: 8
89  * tab-width: 8
90  * indent-tabs-mode: t
91  * End:
92  *
93  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
94  * :indentSize=8:tabSize=8:noTabs=false:
95  */
96