Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active January 25, 2020 14:54
Show Gist options
  • Save freddi301/8a370561e8fc87c4c457fc3a6d1dc89a to your computer and use it in GitHub Desktop.
Save freddi301/8a370561e8fc87c4c457fc3a6d1dc89a to your computer and use it in GitHub Desktop.
calculate ipv4 broadcast address typescript
function getBroadcastAddress({ address, netmask }: NetworkInterfaceInfo) {
const addressBytes = address.split(".").map(Number);
const netmaskBytes = netmask.split(".").map(Number);
const subnetBytes = netmaskBytes.map(
(_, index) => addressBytes[index] & netmaskBytes[index]
);
const broadcastBytes = netmaskBytes.map(
(_, index) => subnetBytes[index] | (~netmaskBytes[index] + 256)
);
return broadcastBytes.map(String).join(".")
}
/*
// test
getBroadcastAddress({ address: "192.168.1.93", netmask: "255.255.255.0" }) == '192.168.1.255'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment