doulei3488 2016-06-09 18:23
浏览 95
已采纳

Go / GoLang反向二进制数据以查找广播地址

I try to invert the binary in golang to find broadcast ip address from the input data.

10000010.00101101.00100000.00000000   (network adress)
OR
00000000.00000000.00001111.11111111   (inverted subnet mask)
=
10000010.00101101.00101111.11111111 = 130.45.47.255 (broadcast address)

Assume user input

network address 130.45.32.0
subnetmask      255.255.240.0    11111111.11111111.11110000.00000000
// expect invert subnetmask      00000000.00000000.00001111.11111111

So if I got subnet mask from user input now I need to invert it

// subIp from https://golang.org/pkg/net/#IP.Mask
subIp:=subnetmask.Mask(network.Mask)
//                  255.      255.      240.       0
// then I loop to subIp[0], subIp[1], subIp[2], subIp[3]    
// I Assume subIp[3] = 0
subnet := int64(subIp[3])
subnetString := strconv.FormatInt(subnet, 2)

// add 0 before number
subnetString = leftPad2Len(subnetString, "0", 8)

// loop to string and invert it
invertSubnetString := ""
for i := 0; i<8; i++ {
    if subnetString[i] == 48 {
        invertSubnetString += "1"
    } else {
        invertSubnetString += "0"
    }
}

// now I got invert data. So I can find broadcast number
// convert it to int
invertSubnet, _ := strconv.ParseInt(invertSubnetString, 2, 64)

// then OR
fmt.Println(networkIp | invertSubnet)

Are there any easy way to do the thing like I do ?

  • 写回答

1条回答 默认 最新

  • dqrq93879 2016-06-09 19:26
    关注

    You can manipulate the bytes of the address directly, without converting to strings:

    https://play.golang.org/p/FfLu7Gb1HT

    mask := net.CIDRMask(20, 32)
    ip := net.IP([]byte{140, 45, 32, 0})
    
    broadcast := net.IP(make([]byte, 4))
    for i := range ip {
        broadcast[i] = ip[i] | ^mask[i]
    }
    
    fmt.Println(broadcast)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。