-
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
-
49
-
50
-
51
-
52
-
53
-
54
-
55
// Copyright 2025 Shota FUJI
//
// Licensed under the Zero-Clause BSD License or the Apache License, Version 2.0, at your option.
// You may not use, copy, modify, or distribute this file except according to those terms. You can
// find a copy of the Zero-Clause BSD License at LICENSES/0BSD.txt, and a copy of the Apache License,
// Version 2.0 at LICENSES/Apache-2.0.txt. You may also obtain a copy of the Apache License, Version
// 2.0 at <https://www.apache.org/licenses/LICENSE-2.0>
//
// SPDX-License-Identifier: 0BSD OR Apache-2.0
//! This module contains cross-platform, pure Zig functions for computing a broadcast address in
//! IPv4 subnet.
const std = @import("std");
/// Helper function to get a broadcast address for a subnet.
/// If your platform have this functionality, use that instead.
pub inline fn getBroadcastAddressU32(ipv4_addr: u32, netmask: u32) u32 {
return ipv4_addr | (~netmask);
}
test getBroadcastAddressU32 {
// Addresses are borrowed from here: <https://en.wikipedia.org/wiki/Broadcast_address>
try std.testing.expectEqual(
0xac1fffff,
getBroadcastAddressU32(0xac100000, 0xfff00000),
);
}
/// Helper function to get a broadcast address for a subnet.
/// This variant operates on an array.
/// If your platform have this functionality, use that instead.
pub inline fn getBroadcastAddress(ipv4_addr: *const [4]u8, netmask: *const [4]u8) [4]u8 {
var result: [4]u8 = undefined;
std.mem.writeInt(u32, &result, getBroadcastAddressU32(
std.mem.readInt(u32, ipv4_addr, .big),
std.mem.readInt(u32, netmask, .big),
), .big);
return result;
}
test getBroadcastAddress {
try std.testing.expectEqualDeep(
&[4]u8{ 192, 168, 1, 255 },
&getBroadcastAddress(&.{ 192, 168, 1, 1 }, &.{ 255, 255, 255, 0 }),
);
// Addresses are borrowed from here: <https://en.wikipedia.org/wiki/Broadcast_address>
try std.testing.expectEqualDeep(
&[4]u8{ 172, 31, 255, 255 },
&getBroadcastAddress(&.{ 172, 16, 0, 0 }, &.{ 255, 240, 0, 0 }),
);
}