Created
March 17, 2022 02:37
-
-
Save cia-rana/e9373200fa0f257c378c16c23616f120 to your computer and use it in GitHub Desktop.
How to calculate Broadcast Address(IPv4) with net/netip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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