Skip to content

Instantly share code, notes, and snippets.

@cia-rana
Created March 17, 2022 02:37
Show Gist options
  • Save cia-rana/e9373200fa0f257c378c16c23616f120 to your computer and use it in GitHub Desktop.
Save cia-rana/e9373200fa0f257c378c16c23616f120 to your computer and use it in GitHub Desktop.
How to calculate Broadcast Address(IPv4) with net/netip
package main
import (
"encoding/binary"
"fmt"
"net/netip"
)
func BAddr(s string) (netip.Addr, error) {
p, err := netip.ParsePrefix(s)
if err != nil {
return netip.Addr{}, err
}
a4 := p.Masked().Addr().As4()
binary.LittleEndian.PutUint32(a4[:], binary.LittleEndian.Uint32(a4[:])|1<<(31-p.Bits()))
return netip.AddrFrom4(a4).Prev(), nil
}
func main() {
s := "192.168.1.1/24"
fmt.Println(s)
fmt.Println(BAddr(s))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment